如何检查是否存在文件,而不使用试用声明?
当前回答
使用:
import os
#Your path here e.g. "C:\Program Files\text.txt"
#For access purposes: "C:\\Program Files\\text.txt"
if os.path.exists("C:\..."):
print "File found!"
else:
print "File not found!"
进口 OS 使您更容易与您的操作系统一起导航和执行标准操作。
请参见《如何检查没有例外的文件是否存在》。
如果您需要高级操作,请使用Shutil。
其他回答
Python 3.4+ 有一个以对象为导向的路径模块: pathlib. 使用这个新模块,您可以检查是否存在这样的文件:
import pathlib
p = pathlib.Path('path/to/file')
if p.is_file(): # or p.is_dir() to see if it is a directory
# do stuff
在打开文件时,您仍然可以(通常应该)使用尝试/排除区块:
try:
with p.open() as f:
# do awesome stuff
except OSError:
print('Well darn.')
pathlib 模块有很多很好的东西在它:方便的旋转,检查文件的所有者,更容易的路径加入,等等,值得检查。 如果你在更老的 Python (版本 2.6 或更晚),你仍然可以安装 pathlib 带 pip:
# installs pathlib2 on older Python versions
# the original third-party module, pathlib, is no longer maintained.
pip install pathlib2
然后将其输入如下:
# Older Python versions
import pathlib2 as pathlib
>>> from pathlib import Path
>>> Path('/').is_file()
False
>>> Path('/initrd.img').is_file()
True
>>> Path('/doesnotexist').is_file()
False
>>> import os
>>> os.path.isfile('/')
False
>>> os.path.isfile('/initrd.img')
True
>>> os.path.isfile('/doesnotexist')
False
现在上面的可能是最好的实用直接答案在这里,但有可能有一个竞赛条件(取决于你正在尝试实现什么),并且事实上,基础实施使用一个尝试,但Python使用尝试到处在其实施。
更长、更有趣的答案
>>> from pathlib import Path
>>> root = Path('/')
>>> root.exists()
True
>>> root.is_file()
False
is_file(self)
Whether this path is a regular file (also True for symlinks pointing
to regular files).
>>> import tempfile
>>> file = tempfile.NamedTemporaryFile()
>>> filepathobj = Path(file.name)
>>> filepathobj.is_file()
True
>>> filepathobj.exists()
True
>>> del file
>>> filepathobj.exists()
False
>>> filepathobj.is_file()
False
def is_file(self):
"""
Whether this path is a regular file (also True for symlinks pointing
to regular files).
"""
try:
return S_ISREG(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False
from contextlib import suppress
from pathlib import Path
>>> with suppress(OSError), Path('doesnotexist').open() as f:
... for line in f:
... print(line)
...
>>>
>>> with suppress(OSError):
... Path('doesnotexist').unlink()
...
>>>
class suppress(object):
def __init__(self, *exceptions):
self.exceptions = exceptions
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is not None:
return issubclass(exc_type, self.exceptions)
from contextlib import contextmanager
@contextmanager
def suppress(*exceptions):
try:
yield
except exceptions:
pass
import os
os.path.isfile(path)
>>> OSError is os.error
True
try:
with open(path) as f:
f.read()
except OSError:
pass
import os
os.access(path, os.F_OK)
批评另一个答案:
另一个答案是关于os.access:
这个答案说,它更喜欢一个非皮顿,错误的方法,没有理由,似乎鼓励用户使用低级的API,而不理解它们。
它还创建了一个背景管理器,通过无条件返回真相,允许所有例外(包括键盘中断和系统输出!)沉默地通过,这是一个很好的方式来隐藏错误。
import os
os.path.exists(path) # Returns whether the path (directory or file) exists or not
os.path.isfile(path) # Returns whether the file exists or not
使用 os.path.isfile(), os.path.isdir() 和 os.path.exists() 的文件和文件夹进行测试
假设“路径”是有效的路径,此表显示了每个函数为文件和文件夹返回的内容:
此分類上一篇
您还可以测试文件是否是一种特定类型的文件,使用 os.path.splitext() 获取扩展(如果您还不知道)
>>> import os
>>> path = "path to a word document"
>>> os.path.isfile(path)
True
>>> os.path.splitext(path)[1] == ".docx" # test if the extension is .docx
True
exist() and is_file() 对“路”对象的方法可以用来检查是否有一个特定的路径存在并是一个文件。
Python 3 程序检查是否存在文件:
# File name: check-if-file-exists.py
from pathlib import Path
filePath = Path(input("Enter path of the file to be found: "))
if filePath.exists() and filePath.is_file():
print("Success: File exists")
else:
print("Error: File does not exist")
出口:
$ python3 check-if-file-exists.py 输入文件的路径可以找到: /Users/macuser1/stack-overflow/index.html 成功: 文件存在 $ python3 check-if-file-exists.py 输入文件的路径可以找到: hghjg jghj 错误: 文件不存在