[英]data not appending in my output file, python csv module 3.6
I am a newbie to python world, need help 我是python world的新手,需要帮助
I have a requirement to remove the duplicate values from row3 and append the data of row4, I am using below script to achieve this 我需要从row3删除重复的值并追加row4的数据,我正在使用以下脚本来实现这一点
Everything works fine except the data in the row4 is not getting appended 一切工作正常,除了未附加row4中的数据
Appreciate your help on this 感谢您的帮助
import csv
result = {}
with open('test.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
with open('output.csv', 'w',encoding='utf-8') as new_file:
fieldnames = ['row1','row2','row3','row4','row5',]
csv_writer = csv.DictWriter(new_file,lineterminator='\n' , fieldnames=fieldnames)
csv_writer.writeheader ()
for row in csv_reader:
if row["row3"] in result:
result [row["row3"]].append (row["row4"])
else:
result[row["row3"]] = [row["row4"]]
csv_writer.writerow({
"row1": row["row1"],
"row2": row["row2"],
"row3": row["row3"],
"row4": row["row4"],
"row4": row["row4"]
})
Change the 'w' to 'a' in the line: 在行中将“ w”更改为“ a”:
with open('output.csv', 'w',encoding='utf-8') as new_file:
a is for appending to the file. a用于附加到文件。 w is for write, which will overwrite any previous files. w用于写操作,它将覆盖以前的所有文件。
Refer to https://docs.python.org/3/tutorial/inputoutput.html for python file input and outputs 请参阅https://docs.python.org/3/tutorial/inputoutput.html了解python文件的输入和输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.