Pythonically Add Header to a CSV File

Pythonically add header to a csv file

The DictWriter() class expects dictionaries for each row. If all you wanted to do was write an initial header, use a regular csv.writer() and pass in a simple row for the header:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
writer = csv.writer(outcsv)
writer.writerow(["Date", "temperature 1", "Temperature 2"])

with open('t1.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows(row + [0.0] for row in reader)

with open('t2.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

The alternative would be to generate dictionaries when copying across your data:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
writer.writeheader()

with open('t1.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)

with open('t2.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)

How to add a header to a csv file in Python?

All you need to do is call DictWriter.writeheader() without arguments:

with open(os.path.join(directory, 'csv.csv'), 'wb') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames = ["stuff1", "stuff2", "stuff3"], delimiter = ';')
writer.writeheader()

You already told DictWriter() what your headers are.

csv header in python only on the top row?

You could wrap the writerow function to have it automatically add the header if needed.

If your output csv file is not empty, we can assert the header was already written and simply append the row. Otherwise (file not exist or empty) we write the header before appending the row.

import os

def write_row_header_aware(filename, row):

# in case file doesn't exist or is empty
if not os.path.exists(filename) or os.stat(filename).st_size == 0:
# write header
with open(filename, 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(['current_time', 'SHORTPERC', 'LONGPERC', ...])

# write line as usual
with open(filename, 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(row)

write_row_header_aware('data.csv', [current_time, SHORTPERC, LONGPERC, ...])

How to add new column(header) to a csv file from command line arguments

see this post which suggests something like the following:

header = ['User_ID','--Date','0Num_1','0Num_2','Com_ID']
writer = csv.DictWriter(outcsv, fieldnames = header)
writer.writeheader()
writer.writerows({col: row} for row, col in zip(header, p))

to parse the extra columns from the system arguments use sys.argv

import sys

extra_headers = sys.argv
header.extend(sys.argv)
n = len(sys.argv)

writer = csv.DictWriter(outcsv, fieldnames = header)
writer.writeheader()

col_fill = ''
# extend p with two columns of blank data
writer.writerows({col: row_item} for row in p for row_item,col in zip(row+[col_fill]*n,header))

here I iterate through each row, I then crate a dictionary to allocate data to each column in order. Notice [col_fill]*n this creates a list of identical items equal to col_fill that will be used to fill the additional columns parsed in via command line arguments.

In this example the command line arguments would be parsed as:

$ python script_name.py Dept_ID Location

and would create:

User_ID,--Date,0Num_1,0Num_2,Com_ID,Dept_ID,Location
000101,04-13-2015,000012,000021,001011,,
000102,04-03-2014,000001,000007,001002,,
000103,06-05-2013,000003,000004,000034,,
000104,12-31-2012,000004,000009,001023,,
000105,09-09-2011,000009,000005,000104,,

python csv add column name

may be you can add a header like this?

with open(csvfilename, 'wt', newline ='') as file:
write_header = csv.writer(file, delimiter=',')
write_header.writerow(i for i in list[0])

Python Edit CSV headers

The headers are just another row of CSV data. Just write them as a new row to the output followed by the rest of the data from the input file.

import csv
import os

inputFileName = "temp.csv"
outputFileName = os.path.splitext(inputFileName)[0] + "_modified.csv"

with open(inputFileName, 'rb') as inFile, open(outputFileName, 'wb') as outfile:
r = csv.reader(inFile)
w = csv.writer(outfile)

next(r, None) # skip the first row from the reader, the old header
# write new header
w.writerow(['Item Number', 'Item Description', 'List Price', 'QTY Available'])

# copy the rest
for row in r:
w.writerow(row)

For Python 3, use:

with open(inputFileName, newline='') as inFile, open(outputFileName, 'w', newline='') as outfile:

and you may have to specify an encoding for your data.



Related Topics



Leave a reply



Submit