Python - Как проверить, существует ли файл
В Python мы можем использоватьos.path.isfile()
илиpathlib.Path.is_file()
(Python 3.4), чтобы проверить, существует ли файл.
1. pathlib
Новое в 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
Если проверить
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
Классические примерыos.path
.
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
Если проверить.
import os.path fname = "c:\\test\\abc.txt" if os.path.isfile(fname): print("file exist!") else: print("no such file!")
3. Попробуйте: кроме
Мы также можем использоватьtry except
, чтобы проверить, существует ли файл.
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)
Выход
[Errno 2] No such file or directory: 'c:\\test\\no-such-file.txt'