- 1
How to deal with FileNotFoundError?
It appears when i use file.open
2 Antworten
+ 3
You need to be sure that the file exists, and provide a valid path: with absolute ones, not a problem, but for relatives, you need to know the current working dir, or the directory of the source code...
# source code file dir:
# relative to the current working directory active when script start, even you chdir() ^^
print(os.path.dirname(os.path.realpath(__file__)))
# current working directory:
import os
print(os.getcwd())
# change dir:
import os
os.chdir('path')
# test if file exists:
# True if file, False if dir dir or not exists
import os
print(os.path.isfile('filename'))
# test if directory exists:
# True if file or dir, False else
import os
print(os.path.exists('path'))
And you can use try/except statement to catch the error if it occurs:
try:
f = open('myfile.ext')
except IOError:
print('do something when file no exist')
0
provide valid path and make sure file is present in that path provided with right file type