Python Forum
using a try/except in a conditional expression
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
using a try/except in a conditional expression
#2
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) :

>>> 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.
Reply


Messages In This Thread
RE: using a try/except in a conditional expression - by perfringo - Aug-27-2019, 05:45 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020