Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 模式在文件不存在时创建文件_Python - Fatal编程技术网

Python 模式在文件不存在时创建文件

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

我正在尝试使用下面的行写入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 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()告诉您存在什么?