Python How to check if a file exists
By:Roy.LiuLast updated:2019-08-11
In Python, we can use os.path.isfile() or pathlib.Path.is_file() (Python 3.4) to check if a file exists.
1. pathlib
New in Python 3.4
from pathlib import Path fname = Path("c:\\test\\abc.txt") print(fname.exists()) # true print(fname.is_file()) # true print(fname.is_dir()) # false dir = Path("c:\\test\\") print(dir.exists()) # true print(dir.is_file()) # false print(dir.is_dir()) # true
If check
from pathlib import Path fname = Path("c:\\test\\abc.txt") if fname.is_file(): print("file exist!") else: print("no such file!")
2. os.path
A classic os.path examples.
import os.path fname = "c:\\test\\abc.txt" print(os.path.exists(fname)) # true print(os.path.isfile(fname)) # true print(os.path.isdir(fname)) # false dir = "c:\\test\\" print(os.path.exists(dir)) # true print(os.path.isfile(dir)) # false print(os.path.isdir(dir)) # true
If check.
import os.path fname = "c:\\test\\abc.txt" if os.path.isfile(fname): print("file exist!") else: print("no such file!")
3. Try: Except
We can also use the try except to check if a file exists.
fname = "c:\\test\\no-such-file.txt" try: with open(fname) as file: for line in file: print(line, end='') except IOError as e: print(e)
Output
[Errno 2] No such file or directory: 'c:\\test\\no-such-file.txt'
References
From:一号门
COMMENTS