Python 模式在文件不存在时创建文件
我正在尝试使用下面的行写入CSV文件,我认为“ab+”将创建该文件,即使它不存在,但显然它失败了。知道当它不存在时,我应该打开哪种模式来创建该文件吗Python 模式在文件不存在时创建文件,python,Python,我正在尝试使用下面的行写入CSV文件,我认为“ab+”将创建该文件,即使它不存在,但显然它失败了。知道当它不存在时,我应该打开哪种模式来创建该文件吗 #Keep appending date and count everytime this script is run c = csv.writer(open("//location/scripts/" + csv_file + ".csv", "ab+")) 错误:- IOError: [Errno 2] No such file or dir
#Keep appending date and count everytime this script is run
c = csv.writer(open("//location/scripts/" + csv_file + ".csv", "ab+"))
错误:-
IOError: [Errno 2] No such file or directory: '//location/scripts/BT_FM_BUGGY_FIX_CRTREND.csv'
a+
如果文件不存在,是否创建该文件:
>>> import os
>>> from tempfile import mkdtemp
>>> dir = mkdtemp()
>>> os.listdir(dir)
[]
>>> open(os.path.join(dir, 'test.txt'), 'ab+').write('test')
>>> os.listdir(dir)
['test.txt']
但是,该模式不创建目录。要在其中创建文件的目录不存在。首先创建该目录,如果该目录应该已经存在,请更正它。为什么路径开头有两个斜杠?@Martijin Pieters-directoryexists@user2639990:os.listdir()告诉您存在什么?