pathlib (Python 3.4 and Up)On Python versions 3.4 and higher, objects of the built-in pathlib.Path class have a method .exists() which returns True if the path exists on the file system, and False otherwise. For example, to check if the file myfile.txt exists in the user's current directory, we can write:
1 2 3 4 5 6 | from pathlib import Path if Path( 'myfile.txt' ).exists(): print( 'Exists!' ) else: print( 'Does not exist.' ) |
Because Path( 'myfile.txt' ) returns an object, it can also be stored in a variable and we can call .exists() on that variable:
1 2 3 4 5 6 7 8 | from pathlib import Path p = Path( 'myfile.txt' ) if p.exists(): print( 'Exists!' ) else: print( 'Does not exist.' ) |
os.pathOn any version of Python 3, we can alternatively use the built-in os.path module to check if a path exists:
1 2 3 4 5 6 | import os if os.path.exists( 'myfile.txt' ): print( 'Exists!' ) else: print( 'Does not exist.' ) |