At the start of my script, the file script.log
is expected to exist and messages are being appended to it. But if the file does not exist (the user has decided to delete the file), the file should not be created again, the messages will be printed to stdout
instead. Fill the bucket only if you see it.
How to do that?
Loads of people must have had a similar problem but I couldn't find any solution.
if os.path.exists('script.log'):
with open('script.log', 'a') as f:
f.write('foo')
else:
print('foo')
I know that the following code should work but ideally I would like to avoid it because it contains a race condition :
if os.path.exists('script.log'): with open('script.log', 'a') as f: f.write('foo') else: print('foo')
Use os.open
and os.fdopen
separately rather than open
.
The "a"
mode used by open
tries to open the file using the flags os.O_APPEND
and os.O_CREAT
, creating the file if it doesn't already exist. We'll use os.fdopen
to use just the os.O_APPEND
flag, causing a FileNotFoundError
to be raised if it doesn't already exist.
Assuming it succeeds, we'll use os.fdopen
to wrap the file descriptor returned by fdopen
in a file-like object. (This requires, unfortunately, a seemingly redundant "a"
flag.)
import os
import sys
try:
fd = os.open('script.log', os.O_APPEND)
with os.fdopen(fd, "a") as f:
f.write("foo")
except FileNotFoundError:
print("foo")
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.