以写入和追加模式打开文件

时间:2013-07-19 22:01:59

标签: python

我正在尝试将一些数据附加到如下文件中......但是当文件不存在时,这会失败。 我尝试了以下..可以任何人提供关于在两种写模式下打开文件的输入,以便它创建文件,如果它不存在并同时追加模式?

代码: -

c = csv.writer(open("//DATA/loc" + csv_file + ".csv", "ab"))
c.writerow([format_time, icount])

2 个答案:

答案 0 :(得分:3)

使用

c = csv.writer(open("//DATA/loc" + csv_file + ".csv", "a+b"))
c.writerow([format_time, icount])

而不是

c = csv.writer(open("//DATA/loc" + csv_file + ".csv", "ab"))
c.writerow([format_time, icount])

答案 1 :(得分:0)

您是否尝试过w+b模式:

c = csv.writer(open("//DATA/loc" + csv_file + ".csv", "w+b"))