2017-11-30 5 views
1

私は今少しプロジェクトに取り組んでいます。このプロジェクトでは、私はCSVファイルを作成しています。ここでは、コードは:CSVのpythonに書き込むときに空白のセルを破棄します

def process_form_in_csv(self, order_id, order_date, order_fees): 
    file_exists = os.path.isfile(self.SALES_SHEET) 
    with open(self.SALES_SHEET, 'ab') as csvfile: 
    fieldnames = ['Date','Order ID','Fee'] 
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames) 

    if not file_exists: 
     writer.writeheader() 
    writer.writerow({'Date': order_date, 
       'Order ID': order_id,       
       'Seller Fee': order_fees, 
       }) 
    csvfile.close() 

このコードは動作しますが、私はプログラムを再実行するたびに最初の行は、行の下実施し、それがあるべき場所から3つの細胞の上に配置されます。セルを(Excelで)削除すると、それらは残っています。私は何が起こっているのか分からない。添付されているのは、 "空の" csvのイメージです。私はあなたが見てすることをお勧めCSV with deleted content

+0

は、open()関数は 'W' モードを使用するようにしてください。 – GSazheniuk

答えて

0

python open built-in function: difference between modes a, a+, w, w+, and r+?

``a'' Open for writing. The file is created if it does not exist. The 
    stream is positioned at the end of the file. Subsequent writes 
    to the file will always end up at the then current end of file, 
    irrespective of any intervening fseek(3) or similar. 

``w'' Truncate file to zero length or create text file for writing. 
    The stream is positioned at the beginning of the file. 
+1

小冊子が私の頭の上にかかった。私は定義に感謝します。あなたの答えをありがとう。 –

関連する問題