Search code examples
pythonoperating-systemglobal-variables

Exit the program when FileNotFound: [Win Error 3] arises


I am using a for loop to look for various files. Somes when the file with specific is not found, the program stops immediately and raises the Filenotfound error. Instead, I want the program to exit safely when such errors arise. My code:

os.chdir('FileLocation')
all_filenames = [i for i in glob.glob('*.{}'.format(extension))]

Present output:

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:....//2016//01'

Solution

  • try:
        dosomething()
    except FileNotFoundError:
        pass
        ...