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

Dave Angel d at davea.name
Tue Nov 29 10:17:55 CET 2011


On 11/29/2011 03:37 AM, 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."
>
Could you explain what's unclear about it?  Andreas couldn't get more 
specific, since you didn't say how these 10 names are provided.  If 
they're in a list called filenames, you could do something like:

fileobjects = []
for fname in filenames:
     try:
         fileobj = open(fname, "r")
         fileobjects.append(fileobj)
     catch SomeExceptionType as e:
         pass

and when you're done, use something like:

if len(fileobjects) == 0:
      print "no files could be opened"

>
> I thought I could co along those lines earlier
>
> try:
>    text_file=open("Hey","r") and text_file1=open("Hey","r")

Unfortunately this isn't valid Python syntax.  The equal sign has a 
specific statement syntax, and the only time you can have more than one 
of them in one statement, is the chained assignments, where they all get 
bound to the same object.  You wouldn't want to do this anyway, since it 
would leave all those open files in an unspecified state.

To go one step further, if it could work, it would give an exception if 
any ONE of the files couldn't be open, and you want the message to 
appear if none of the files could be opened.

> except:
>    print("hi")
>
>
> So that hi is printed only and only if both files aren't existing.
If you didn't need to open them, but just to make sure they exist, you 
could use if  os.exist(filename)  much more easily.

-- 

DaveA



More information about the Tutor mailing list