Python - So überprüfen Sie, ob eine Datei vorhanden ist
In Python können wiros.path.isfile()
oderpathlib.Path.is_file()
(Python 3.4) verwenden, um zu überprüfen, ob eine Datei vorhanden ist.
1. pathlib
Neu 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
Wenn überprüfen
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
Beispiele für klassischeos.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
Wenn überprüfen.
import os.path fname = "c:\\test\\abc.txt" if os.path.isfile(fname): print("file exist!") else: print("no such file!")
3. Versuch: Außer
Wir können auchtry except
verwenden, um zu überprüfen, ob eine Datei vorhanden ist.
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)
Ausgabe
[Errno 2] No such file or directory: 'c:\\test\\no-such-file.txt'