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’
=== 参考文献 . https://docs.python.org/3/library/pathlib.html#pathlib.Path.is__file[pathlib - オブジェクト指向のファイルシステムのパス]。 https://docs.python.org/3/library/os.path.html[os.path - 共通] パス名操作] リンク://タグ/io/[io]リンク://タグ/os-path/[os.path]link://tag/pathlib/[pathlib]link://タグ/python/[python]