简体   繁体   English

Python CSV 编写器仅写入处理的最后一项

[英]Python CSV Writer only writing last item processed

I am looping through a CSV and creating a new one in 'python3' like this...我正在循环一个 CSV 并像这样在'python3'中创建一个新的......

for row in csvreader:

    with open('employee_file.csv', mode='w', encoding='utf-8') as employee_file:

        employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        employee_writer.writerow([row[0],employeeName])

But once it finished processing I am left with only the last result in employee_file.csv.但是一旦完成处理,我只剩下employee_file.csv 中的最后一个结果。 Where am I going wrong?我哪里错了?

Take the file opening line before the for loop.在 for 循环之前取文件打开行。 The way you have it now you keep writing it over in the for loop.你现在拥有它的方式是在 for 循环中继续编写它。

with open('employee_file.csv', mode='w', encoding='utf-8') as employee_file:
   for row in csvreader:
        ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM