python - Writing a different statement for an error -


i have written program on files i/o in python, contains part file opened i.e

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

in case file not found, want write print statement saying, "sorry, file not found." tried using error handling (for & except), did not work because of nested code after above. appreciated.

thanks

use os.path.isfile:

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

also, if need read text, want do:

if os.path.isfile(f):     open("filename.txt") f         alltext = f.read() else:     # print statement goes here 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -