CSV模块无法写入

问题描述 投票:-3回答:2

我有一些我正在处理的代码,但它不再有效。我已经完成了测试,一切都过去了。 writer.write(row)跑。但是,当我去我的sales_report/2017_sales_final.csv时,文件是空白的。它没有显示in_file的值,大小为0kb。我究竟做错了什么?

fieldnames = ['Date', 'Order ID']
in_file = open('sales_report/hardcopy.csv', 'r')
out_file = open('sales_report/2017_sales_final.csv', "w")
reader = csv.DictReader(in_file, fieldnames=fieldnames)
writer = csv.DictWriter(out_file, fieldnames=fieldnames)

for row in reader:
    writer.writerow(row)

writer.writerow({'Your order': '12/15/2017','Order ID': '696969'})
python python-3.x csv
2个回答
0
投票

可能,您正在查看该文件,但尚未关闭。通过命令行运行脚本可能会正确显示文件内容,因为当Python退出时,文件句柄将被关闭,但如果在IDE中运行,则句柄可能保持打开状态。使用with语句确保您的文件已关闭:

fieldnames = ['Date', 'Order ID']
with open('sales_report/hardcopy.csv', 'r') as in_file:
    with open('sales_report/2017_sales_final.csv', "w") as out_file:
        reader = csv.DictReader(in_file, fieldnames=fieldnames)
        writer = csv.DictWriter(out_file, fieldnames=fieldnames)
        # etc.

# files will be closed outside the with blocks.

-1
投票

你永远不会close输出文件。

© www.soinside.com 2019 - 2024. All rights reserved.