我必须在python中将几个列表作为列添加到现有CSV文件中。我想为输出CSV使用一个临时文件,因为我想对该结果数据的前两列进行排序,然后写入新的最终CSV文件。我不想保留未排序的csv文件,这就是为什么我要在该步骤中使用tempfile.NamedTemporaryFile的原因。最终CSV文件中没有任何内容,但没有其他代码错误。我更改了 with 块的缩进方式,但无法修复。我通过使用磁盘上的文件进行了测试,效果很好。我需要帮助来了解我在做什么错。这是我的代码:
# Open the existing csv in read mode and new temporary csv in write mode
with open(csvfile.name, 'r') as read_f, \
tempfile.NamedTemporaryFile(suffix='.csv', prefix=('inter'), mode='w', delete=False) as write_f:
csv_reader = csv.reader(read_f)
csv_writer = csv.writer(write_f)
i = 0
for row in csv_reader:
# Append the new list values to that row/list
row.append(company_list[i])
row.append(highest_percentage[i])
# Add the updated row / list to the output file
csv_writer.writerow(row)
i += 1
with open(write_f.name) as data:
stuff = csv.reader(data)
sortedlist = sorted(stuff, key=operator.itemgetter(0, 1))
#now write the sorted result into final CSV file
with open(fileout, 'w', newline='') as f:
fileWriter = csv.writer(f)
for row in sortedlist:
fileWriter.writerow(row)
答案 0 :(得分:0)
您应该插入一个write_f.seek(0, 0)
在打开临时文件的行之前:
write_f.seek(0, 0)
with open(write_f.name) as data:
答案 1 :(得分:0)
我发现了导致IndexError的原因,并因此导致了空的最终CSV。我借助CSV file written with Python has blank lines between each row解决了这个问题。这是我更改后的代码,可以正常运行:
with open(csvfile.name, 'r') as read_f, \
tempfile.NamedTemporaryFile(suffix='.csv', prefix=('inter'), newline='', mode='w+', delete=False) as write_f:
csv_reader = csv.reader(read_f)
csv_writer = csv.writer(write_f)
i = 0
for row in csv_reader:
# Append the new list values to that row/list
row.append(company_list[i])
row.append(highest_percentage[i])
# Add the updated row / list to the output file
csv_writer.writerow(row)
i += 1
with open(write_f.name) as read_stuff, \
open(fileout, 'w', newline='') as write_stuff:
read_data = csv.reader(read_stuff)
write_data = csv.writer(write_stuff)
sortedlist = sorted(read_data, key=operator.itemgetter(0, 1))
for row in sortedlist:
write_data.writerow(row)