[Tutor] How to use try and except in this case?
Steven D'Aprano
steve at pearwood.info
Tue Nov 29 13:26:01 CET 2011
Mic wrote:
> Say that I want to try and open 10 files. If none of these exists, I
> want an error
> message to appear. But only if NONE of these files exists.
>
> I know how to handle this with one file. But I don't know how to do that
> with more than one.
> So the program should try and open all 10 files and if, and only if,
> none of the files exists I want en error message to appear.
Your description isn't quite clear enough. What happens if, say, only 3 of the
files exist? Is the intention to open the first file that you can find?
# Ten file names to try:
names = ['file 1', 'file 2', 'a', 'b', 'c', 'backup file',
'backup file 2', 'spam', 'ham', 'eggs'
]
# Find the first one that exists and is readable.
for name in names:
try:
f = open(name, 'r')
except (OSError, IOError):
continue # try the next one
break # this only runs when a file opens successfully
else:
# we didn't break
raise ValueError('no file could be opened')
Or is it your intention to open as many of the files as possible?
# Ten file names to try:
names = ['file 1', 'file 2', 'a', 'b', 'c', 'backup file',
'backup file 2', 'spam', 'ham', 'eggs'
]
files = [] # list of opened file objects
for name in names:
try:
f = open(name, 'r')
files.append(f)
except (OSError, IOError):
continue # missing, go on to the next one
if files == []:
raise ValueError('no file could be opened')
else:
# do stuff with the files...
# ...
# ...
# don't forget to close them when done (optional but recommended)
for f in files:
f.close()
--
Steven
More information about the Tutor
mailing list