How to deal with FileNotFoundError? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
- 1

How to deal with FileNotFoundError?

It appears when i use file.open

25th Feb 2017, 3:41 PM
Parth Bhore
Parth Bhore - avatar
2 Réponses
+ 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')
26th Feb 2017, 3:20 AM
visph
visph - avatar
0
provide valid path and make sure file is present in that path provided with right file type
25th Feb 2017, 4:26 PM
Raj Kumar Chauhan
Raj Kumar Chauhan - avatar