[英]python joining two csv files
I have two .csv files, headers.csv
and corrected.csv
. 我有两个.csv文件,
headers.csv
和corrected.csv
。 The headers.csv
has all the headers, and the corrected.csv
is just a bunch of organized data. headers.csv
具有所有头,而corrected.csv
只是一堆有组织的数据。
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 "['displacement', 'load', 'cputime', ...]"
is all written to column A while I want displacement in column A, load in column B, cputime in column C, etc. I also want to get rid of the ', ", [], and whitespace
so the end result is exactly like my example above. Thanks in advance! 但是结果是,
"['displacement', 'load', 'cputime', ...]"
全部写入了A列,而我想在A列中进行置换,在B列中加载,在C列中cputime,等。我也想摆脱', ", [], and whitespace
因此最终结果与上面的示例完全相同。在此先感谢您!
假设您有一排用逗号分隔的列名,请尝试: headers = next(csv.reader(open('headers.csv')))
Using python to concatenate the files seems overkill - 使用python连接文件似乎过分了-
cat headers.csv corrected.csv > merged.csv
If you have to/ for some reason want to use Python, Jon Clements has the right idea. 如果您出于某些原因不得不/或想要使用Python,那么Jon Clements就是正确的主意。
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. 在第一行中,您将创建一个包含headers.csv中所有行的列表(理解列表),这就是为什么要使用[]等的原因。
Try with this (from the top of my mind): 尝试一下(从我的脑海中):
headers = csv.reader(open('headers.csv', 'rb'))[0]
Which should return the first row only. 哪个应该只返回第一行。
I'd just hide the fact that you have multiple files from the csv module: 我只是掩盖了您在csv模块中有多个文件的事实:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.