Python Joining Two Csv Files
I have two .csv files, headers.csv and corrected.csv. Theheaders.csv has all the headers, and the corrected.csv is just a bunch of organized data. headers.csv: displacem
Solution 1:
Assuming that you have a single row with comma delimited column names, try: headers = next(csv.reader(open('headers.csv')))
Solution 2:
Using python to concatenate the files seems overkill -
cat headers.csv corrected.csv > merged.csv
If you have to/ for some reason want to use Python, Jon Clements has the right idea.
Solution 3:
In the first line you are creating a list (a comprehension list) with all the lines in headers.csv, that's why you have the [], etc.
Try with this (from the top of my mind):
headers = csv.reader(open('headers.csv', 'rb'))[0]
Which should return the first row only.
Solution 4:
I'd just hide the fact that you have multiple files from the csv module:
import csv
defcat(*files):
for f in files:
withopen(f) as fobj:
for line in fobj:
yield line
writer = csv.writer(open('merged.csv', 'wb'))
for row in csv.reader(cat('headers.csv', 'corrected.csv')):
writer.writerow(row)
Post a Comment for "Python Joining Two Csv Files"