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'