Aug-27-2019, 05:45 AM
If usage case is to write data to a file, but only if it doesn’t already exist then 'x' can be used (from Python Cookbook 3rd edition by Brian K. Jones and David Beazley) :
One can easily catch FileExistsError with try..except.
>>> with open('somefile', 'wt') as f: ... f.write('Hello\n') ... >>> with open('somefile', 'xt') as f: ... f.write('Hello\n') ... Traceback (most recent call last): File "<stdin>", line 1, in <module> FileExistsError: [Errno 17] File exists: 'somefile'If the file is binary mode, use mode xb instead of xt.
One can easily catch FileExistsError with try..except.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.