I am using the following codes to write some log into a new file, every time I run the program. But it seems like that os.path.exists() is creating all the files every time I run it. I am using a mac with 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")
If I run the python script in terminal, ie, "python ./that_code.py" or in IDE, .exists()
will create the files. But simply running .exists()
in IPython will not create the file.
You're completely correct that
for idx in range(0, 100):
if os.path.exists(str(idx) + ".out.txt"):
continue
else:
output_file = open(str(idx) + ".out.txt", "w")
...creates all the files in question. You're entirely wrong that it's the os.path.exists()
line doing it.
output_file = open(str(idx) + ".out.txt", "w")
...creates the files it opens for write. Replace that line with pass
, or just delete the else
clause entirely, and you'll see that creation no longer takes place.
Incidentally -- in Go, this pattern would be considered bad practice, and someone wanting to ensure that these hundred files exist would be advised to open them for write unconditionally, without checking whether they existed previously. This approach avoids race conditions -- what happens if the file's existence changes between the os.path.exists()
call and the open()
-- and also reduces stat()
calls.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.