Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.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 os.path.exists()将创建该文件_Python_Macos_Python 2.7 - Fatal编程技术网

Python os.path.exists()将创建该文件

Python os.path.exists()将创建该文件,python,macos,python-2.7,Python,Macos,Python 2.7,每次运行程序时,我都使用以下代码将一些日志写入新文件。但似乎os.path.exists()每次运行时都在创建所有文件。我使用的是mac和OS X 10.10.3 for idx in range(0, 100): if os.path.exists(str(idx) + ".out.txt"): continue else: output_file = open(str(idx) + ".out.txt", "w") 如果我在终端中运行pyth

每次运行程序时,我都使用以下代码将一些日志写入新文件。但似乎os.path.exists()每次运行时都在创建所有文件。我使用的是mac和OS X 10.10.3

for idx in range(0, 100):
    if os.path.exists(str(idx) + ".out.txt"):
        continue
    else:
        output_file = open(str(idx) + ".out.txt", "w")

如果我在终端中运行python脚本,即“python./that_code.py”或在IDE中运行,则
.exists()
将创建文件。但是在IPython中只运行
.exists()
不会创建文件。

您完全正确

for idx in range(0, 100):
    if os.path.exists(str(idx) + ".out.txt"):
        continue
    else:
        output_file = open(str(idx) + ".out.txt", "w")
…创建所有相关文件。你完全错了,这是由
os.path.exists()
行执行的

        output_file = open(str(idx) + ".out.txt", "w")
…创建它打开以进行写入的文件。将该行替换为
pass
,或者完全删除
else
子句,您将看到不再进行创建



顺便说一句——在Go中,这种模式被认为是不好的做法,希望确保这一百个文件存在的人会被建议无条件地打开它们进行写入,而不检查它们以前是否存在。这种方法避免了竞争条件——如果文件的存在性在
os.path.exists()
调用和
open()
调用之间发生变化,就会发生这种情况——并且还减少了
stat()
调用。

听起来,如果文件不存在,就要创建文件,但如果文件存在,就不要对其进行破坏。在这种情况下,您可能希望(如达菲先生所建议的那样,无条件地)打开文件进行追加(
“a”
),而不是进行写入(
“w”
)。@Edward那么,您就不能无条件地打开它进行追加吗?修复方法可能是在
输出文件=…
行之后添加一个
中断(
。@EthanFurman,这取决于OP真正想要做什么。也许他们想预先创建所有一百个文件,以避免以后inode耗尽的任何机会。如果他们不打算告诉我们他们的意图,为什么还要再猜测呢强迫人们在得到好的答案之前澄清他们的问题意味着他们将来可能会想写一个更好的问题。这是一个愚蠢的错误,在
输出文件=…
行之后应该有一个
中断。