[Tutor] How to handle try and except in this case

Peter Otten __peter__ at web.de
Tue Nov 29 10:30:30 CET 2011


Mic wrote:

> 
> On 2011-11-27 17:58, 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.
> 
> 
> [Andreas wrote]:
>>Use a counter which increments with every existing file. After opening
>>all files check if the counter is bigger than 0.
> 
>>Or, if you need to know which files exist, use a list, append existing
>>files to it and check at the end if it's not empty.
> 
>>Do you need more help?
> 
> Andreas,
> 
> 
> Thanks for your answer. I am afraid I don't understand this:
> "Use a counter which increments with every existing file. After opening
> all files check if the counter is bigger than 0."
> 
> 
> I thought I could co along those lines earlier
> 
> try:
>     text_file=open("Hey","r") and text_file1=open("Hey","r")
> except:
>     print("hi")
> 
> 
> So that hi is printed only and only if both files aren't existing.

filenames = ["file1.txt", "file2.txt"]
files = []
for name in filenames:
    try:
        files.append(open(name))
    except IOError:
        pass
if not files:
    print("couldn't open any files")

If you don't need the file objects:

filenames = ["file1.txt", "file2.txt"]
if not any(os.path.exists(name) for name in filenames):
   print("didn't find any existing files")




More information about the Tutor mailing list