6

i have a txt file i would like to use in my program named animallog1.txt. How do i open it so that it can be used in my program using try and except. I know how to use the file using open function but not using try except. Could someone tell me how it is done

rggod
  • 611
  • 5
  • 11
  • 19
  • 1. It is unclear what you are asking, but here is your possible answer: http://stackoverflow.com/questions/8380006/file-open-function-with-try-except-python-2-7-1 2. Try to put at least minimal research effort before asking such questions. `try-except` clause is a standard python combination and if you'd open docs you'll get the idea that you can't open file with try and except... – sashkello Nov 25 '13 at 03:55
  • You can't open a file with `try...except`. I think what's being asked is to open the file like you usually would and catch exceptions if they occur using `try...except`. – Blender Nov 25 '13 at 03:55
  • Maybe this is what you want? http://www.diveintopython.net/file_handling/ – chuthan20 Nov 25 '13 at 03:55

2 Answers2

12

You're very vague, but I'll try and answer your question. The reason you use try and except is to catch an error. In opening a file you would get an IOError. So this is how you would open a file as such:

try:
    with open("file.txt","r") as f:
        #stuff goes here
except IOError:
    #do what you want if there is an error with the file opening
Ryan Saxe
  • 17,123
  • 23
  • 80
  • 128
1

Try Except is not a method of doing something. It's a way of handling errors. Check out this page for more info. Basically, if you think you're going to get an error, you put the code you think will produce an error in the try. Then, you put code you'd like to execute if the error does happen in the except.

For example:

try:
    a = int("apple")
except ValueError:
    a = "apple"

What is happening here is that in the try statement, the line produces a ValueError. It's caught in the except clause and the lines there are computed instead.

So, for you what I would recommend is:

try:
    f = open("test.txt", "r")
except IOError:    #This means that the file does not exist (or some other IOError)
    print "Oops, no file by that name"