如何检查是否存在文件,而不使用试用声明?
当前回答
使用 os.path.isfile() 与 os.access():
import os
PATH = './file.txt'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
print("File exists and is readable")
else:
print("Either the file is missing or not readable")
其他回答
它被认为是更好的风格,避免赛车条件。
不要用我的话来支持这个理论,这里有几个:
风格:本课程的“处理异常条件”部分为软件设计(2007) 避免竞赛条件
你可以写布莱恩的建议,没有尝试:
from contextlib import suppress
with suppress(IOError), open('filename'):
process()
suppress 是 Python 3.4 的组成部分。在旧版本中,您可以快速写下自己的 suppress:
from contextlib import contextmanager
@contextmanager
def suppress(*exceptions):
try:
yield
except exceptions:
pass
这里是一个单线的Python命令为Linux命令线环境,我觉得这是非常有用的,因为我不是那么热的Bash男孩。
python -c "import os.path; print os.path.isfile('/path_to/file.xxx')"
如果您已经进口了NumPy用于其他用途,那么不需要进口其他图书馆,如Pathlib,OS,路径等。
import numpy as np
np.DataSource().exists("path/to/your/file")
这将根据它的存在返回真实或虚假。
您可以使用Python的“OS”图书馆:
>>> import os
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.txt")
True
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.tx")
False
推荐文章
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字
- Pipenv:命令未找到
- 根据Pandas中的另一列提取列值
- virtualenv和pyenv是什么关系?