-2

I have written a program on Files I/O in Python, which contains a part where the file is opened i.e

....
f = open("<filename.txt", "r")
alltext = f.readlines()
....

In the case where the file is not found, I want to write a print statement saying, "Sorry, file not found." I tried using error handling (for & except), which did not work well because of the nested code after the above. Any help would be appreciated.

Thanks

craig-nerd
  • 718
  • 1
  • 12
  • 32
  • 1
    it's `try & except` I guess ? – ZdaR May 15 '15 at 11:48
  • 1
    _"I tried using error handling (for & except), which did not work well"_. Let's see your attempt. "there's nested code after this" does not disqualify try-except from working. – Kevin May 15 '15 at 11:51

1 Answers1

2

Use os.path.isfile:

https://docs.python.org/2/library/os.path.html#os.path.isfile

Also, if you need to read all text, you probably want to do:

if os.path.isfile(f):
    with open("filename.txt") as f
        alltext = f.read()
else:
    # print statement goes here
  • If the file is removed by an other program (or process or thread) between the calls to `isfile` and `open` this will crash. Read [LBYL vs. EAFP](http://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python). – Matthias May 15 '15 at 12:04
  • I am aware of this, but, I don't want to be too dogmatic about it. I am not even sure there is a specific exception for a missing file. If the OP means really to know if a file exists, os.path.isfile is still preferable IMO. OTOH to make a less brittle program, opening files should be surrounded by try/except. –  May 15 '15 at 12:09