如何检查是否存在文件,而不使用试用声明?
当前回答
您可以使用 os.listdir 检查文件是否在特定目录中。
import os
if 'file.ext' in os.listdir('dirpath'):
#code
其他回答
添加一个更轻微的变化,这在其他答案中不完全反映。
这将处理文件_路径是无或空的字符串的情况。
此分類上一篇
def file_exists(file_path):
if not file_path:
return False
elif not os.path.isfile(file_path):
return False
else:
return True
添加基于Shahbaz的建议的变量
def file_exists(file_path):
if not file_path:
return False
else:
return os.path.isfile(file_path)
添加基于Peter Wood的建议的变量
def file_exists(file_path):
return file_path and os.path.isfile(file_path):
使用 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
如果你正在检查的原因是,所以你可以做一些类似的文件_存在: open_it(),它更安全地使用一个尝试周围试图打开它。
如果您不打算立即打开文件,您可以使用 os.path.isfile。
如果路径是现有常规文件,则返回是真实的,这跟随了象征性链接,因此 islink() 和 isfile() 都可以对同一条路径是真实的。
import os.path
os.path.isfile(fname)
如果你需要确保它是一个文件。
从 Python 3.4 开始,Pathlib 模块提供一个以对象为导向的方法(在 Python 2.7 中返回Pathlib2):
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists
要查看一个目录,请:
if my_file.is_dir():
# directory exists
要检查路径对象是否存在,无论它是否是一个文件或目录,使用存在():
if my_file.exists():
# path exists
您也可以在尝试区块中使用 resolve(strict=True):
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists
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
使用:
import os
# For testing purposes the arguments defaulted to the current folder and file.
# returns True if file found
def file_exists(FOLDER_PATH='../', FILE_NAME=__file__):
return os.path.isdir(FOLDER_PATH) \
and os.path.isfile(os.path.join(FOLDER_PATH, FILE_NAME))
它基本上是一个文件夹检查,然后使用 os.path.join 使用适当的目录分离器进行文件检查。
推荐文章
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字
- Pipenv:命令未找到
- 根据Pandas中的另一列提取列值
- virtualenv和pyenv是什么关系?