【发布时间】:2020-08-18 17:48:39
【问题描述】:
我有一个 CSV 文件名“sample.csv”,它有一些列:
id name contactno. fileName
1 robin 1234455 info_v1.csv
2 elsa,roy 42342442 info_v1.csv
3 john 232323 info_v2.csv
fileName 列中提到的文件包含一些文本消息。
info_v1.csv
id message
1 my name is robin. I am from Berlin
2 my name is Elsa. My age is 12
info_v2.csv
id message
3 my name is John.I play football.
现在我想创建一个包含所有信息的文件。例如:
输出.csv
id name contactno. message
1 robin 1234455 my name is robin. I am from Berlin
2 elsa,roy 42342442 my name is Elsa. My age is 12
3 john 232323 my name is John.I play football.
我到目前为止所做的如下:
csvfile = csv.reader(open('sample.csv', newline='',encoding="utf8"))
next(csvfile)
included_cols = [0, 1, 2, 3]
for row in csvfile:
content = list(row[i] for i in included_cols)
filename=content[3]
with open(filename, newline='') as f:
reader = csv.reader(f)
next(reader)
for row1 in reader:
content1 = row1
my_list1=content+content1
但在这里我无法将所有信息保存在一起以创建 output.CSV,我如何匹配 id 以便它不会从 info.csv 中获取错误的数据?
【问题讨论】:
-
文件实际上是 CSV(逗号分隔)到 TSV(制表符分隔)吗?因为似乎是 TSV,尤其是在此字段中使用逗号:
elsa,roy。 -
逗号分隔,但 elsa 是 firstName 而 Roy 是 lastName
标签: python python-3.x list python-2.7