【发布时间】:2018-03-17 13:37:58
【问题描述】:
基本上我有 2 个 csv 文件如下:
File 1: File 2: Current output:
Num Num2 Num
1 1 1
2 2 2
3 3 3
4 4 4
Num2
1
2
3
4
我想将它们合并成一个单独的 csv 文件,如下所示:
Expected File 3:
Num Num2
1 1
2 2
3 3
4 4
但是,当我合并文件时,它从文件 1 数据的底部开始。如何让它们从第 2 列第 1 行开始,而不是从下面开始。
inputs = ["asd.csv", "b.csv"] # etc
# First determine the field names from the top line of each input file
# Comment 1 below
fieldnames = []
for filename in inputs:
with open(filename, "r", newline="") as f_in:
reader = csv.reader(f_in)
headers = next(reader)
for h in headers:
if h not in fieldnames:
fieldnames.append(h)
# Then copy the data
with open("out.csv", "w", newline="") as f_out: # Comment 2 below
writer = csv.DictWriter(f_out, fieldnames=fieldnames)
for filename in inputs:
with open(filename, "r", newline="") as f_in:
reader = csv.DictReader(f_in) # Uses the field names in this file
for line in reader:
# Comment 3 below
writer.writerow(line)
【问题讨论】:
-
您希望 '
Num 1 Num 2在单个列中?