We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,676 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

problem with try function

I am trying to catch error on file input/output. The try functions works fine but as it pass to the next line my code breaks. How can I exit gracefully when the 'infile' doesnt exist?

try:
    infile = open ('Book1.txt', "r")
    
    
except IOError:
    print "input file %s is missing" %'Book1.txt'


tex1 = infile.readline()
outfile = open ('Book11.txt', "w")
while tex1:
    rfields = tex1.split()

    # do something


    print >> outfile, 'something'


outfile.close()
infile.close()

the error message I got:

input file Book1.txt is missing
Traceback (most recent call last):
File "D:\pythonLearing\trial.py", line 11, in <module>
tex1 = infile.readline()
NameError: name 'infile' is not defined

Thank you in advance.

3
Contributors
3
Replies
1 Day
Discussion Span
1 Year Ago
Last Updated
4
Views
Question
Answered
chebude
Newbie Poster
24 posts since Nov 2008
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Put the code under the try or in a function and call the function under the try

def read_file(infile):
    tex1 = infile.readline()
    outfile = open ('Book11.txt', "w")
    while tex1:
        rfields = tex1.split()

    # do something


    print >> outfile, 'something'


    outfile.close()
    infile.close()

try:
    infile = open ('Book1.txt', "r")
    read_file(infile)
    
except IOError:
    print "input file %s is missing" %'Book1.txt'
except:
    print "Some other error"
woooee
Posting Maven
2,703 posts since Dec 2006
Reputation Points: 827
Solved Threads: 779
Skill Endorsements: 9

else part of try is for the case of no exception happened, there is exit function and same you can do also by raising SystemExit, using function like above is also good idea to organize code. You can raise exception in function and handle it in calling function if you end except with raise.

pyTony
pyMod
Moderator
6,300 posts since Apr 2010
Reputation Points: 879
Solved Threads: 986
Skill Endorsements: 26
Question Answered as of 1 Year Ago by woooee and pyTony

Thanks a lot. That was a great help

chebude
Newbie Poster
24 posts since Nov 2008
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0665 seconds using 2.68MB