写入CSV python时销毁空白单元格

时间:2017-11-30 17:28:01

标签: python excel csv

我现在一直在做一个项目。这个项目我正在打开一个CSV文件进行写作。这是代码:

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

1 个答案:

答案 0 :(得分: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.