我有一些我正在处理的代码,但它不再有效。我已经完成了测试,一切都过去了。 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退出时,文件句柄将被关闭,但如果在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.
你永远不会close
输出文件。