Python connects two csv files

I have two CSV files, headers.csvand corrected.csv. headers.csvIt has all the headers, but corrected.csvjust a bunch of organized data.

headers.csv:           
displacement, load, cputime, ...

corrected.csv:            
-990.478170,-0.000026,15:08:06, ...              
-990.038170,-0.000026,15:08:06, ...

The end goal is to be like this example:      
displacement,load,cputime, ...          
-990.478170,-0.000026,15:08:06, ...              
-990.038170,-0.000026,15:08:06, ...

What I have:

headers = [x for x in csv.reader(open('headers.csv', 'rb'))]
writer = csv.writer(open('merged.csv', 'wb'))
writer.writerow(headers)
for row in csv.reader(open('corrected.csv', 'rb')):
    writer.writerow(row)

The result, however, is that it is "['displacement', 'load', 'cputime', ...]"written to column A, but I want an offset in column A, a load in column B, cputime in column C, etc. I also want to get rid of ', ", [], and whitespacetherefore the end result exactly matches my example above. Thanks in advance!

+1
source share
4 answers

Assuming you have a single line with comma delimited column names, try: headers = next(csv.reader(open('headers.csv')))

+2
source

python -

cat headers.csv corrected.csv > merged.csv

/ - Python, Jon Clements .

+2

In the first line, you create a list (a list of concepts) with all the lines in headers.csv, so you have [], etc.

Try this (from the top of my mind):

headers = csv.reader(open('headers.csv', 'rb'))[0]

Which should return only the first line.

+1
source

I just hide the fact that you have several files from the csv module:

import csv

def cat(*files):
    for f in files:
        with open(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)
+1
source

Source: https://habr.com/ru/post/1584160/


All Articles