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.
I aimed at something like the following code but the append mode does not trigger any exception when the file is not found:
try:
with open('script.log', 'a') as f:
f.write('foo')
except FileNotFoundError:
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')