将csv中的某些列附加到另一个csv文件并不会溢出每一行



我找到了一个小python代码,用另一个csv文件中的选定列创建一个新的csv文件它几乎可以正常工作,只是没有在新行上显示每一行。它目前在同一条线上。

这是代码:

import csv
file_name =  'input.csv'
output_file = 'output.csv'
csv_file = open(file_name, 'r')
## note that the index of the year column is excluded
column_indices = [0,1,25,23,5,6,9,27,28,31,33,34,37,72,73,76,105,106,109,45,46,49]
with open(output_file, 'w') as fh:
reader = csv.reader(csv_file, delimiter=',')
for row in reader:
tmp_row = []
for col_inx in column_indices:
tmp_row.append(row[col_inx])
fh.write(','.join(tmp_row))

在最后一列之后,我需要它来创建一个新行,而当前所有内容都在同一行上

使用csv.writer.writerow,或者写入换行符。一个选项是将printfile=选项一起使用:

# replace this
# fh.write(','.join(tmp_row))
# with any of these:
print(*tmp_row, sep=",", file=fh) # default is end="n" so you get rows
fh.writelines([','.join(tmp_row)])
fh.write(','.join(tmp_row) + 'n')

最新更新