2017-12-15 6 views
-3

私が作業していたコードがいくつかありますが、もう機能しません。私はテストを実行し、すべてが合格します。 writer.write(row)が実行されます。しかし、私がsales_report/2017_sales_final.csvに行くと、そのファイルは空白になります。 in_fileの値は表示されず、サイズは0kbです。私は間違って何をしていますか?書き込みに失敗したCSVモジュール

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'}) 
+1

ここのコードは大丈夫です。入力ファイルにデータがありますか?フィールド名が変更された可能性はありますか? –

+0

Python 3でcsvファイルを開くときには必ず 'newline = '''キーワード引数を指定してください。 – martineau

+1

最後の行は非常に奇妙に見えます。フィールド名は「日付」と「注文ID」ですが、最後の行では異なる名前が使用されています。 order_dateとorder_idはどこから来たのですか?あなたは役に立つ助けを得るためにMCVE(googleそれ)を投稿しなければなりません。 – barny

答えて

-1

出力ファイルはcloseではありません。

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. 
関連する問題