Computer Science Atlas
Code Review

Python 3 Examples: Check If a File Exists

May 4, 2021
 

Using 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:

Copy
from pathlib import Path

if Path( 'myfile.txt' ).exists():
    print( 'Exists!' )
else:
    print( 'Does not exist.' )
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:

Copy
from pathlib import Path

p = Path( 'myfile.txt' )

if p.exists():
    print( 'Exists!' )
else:
    print( 'Does not exist.' )
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.' )

Using os.path

On any version of Python 3, we can alternatively use the built-in os.path module to check if a path exists:

Copy
import os

if os.path.exists( 'myfile.txt' ):
    print( 'Exists!' )
else:
    print( 'Does not exist.' )
1
2
3
4
5
6
import os

if os.path.exists( 'myfile.txt' ):
    print( 'Exists!' )
else:
    print( 'Does not exist.' )

References