我有一些我正在处理的代码,但它不再有效。我已经完成了测试,一切都过去了。 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'})
答案 0 :(得分: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 :(得分:-1)
You never close
the output file.