如何检查是否存在文件,而不使用试用声明?
当前回答
使用:
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 使用适当的目录分离器进行文件检查。
其他回答
它被认为是更好的风格,避免赛车条件。
不要用我的话来支持这个理论,这里有几个:
风格:本课程的“处理异常条件”部分为软件设计(2007) 避免竞赛条件
使用 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")
这里是一个单线的Python命令为Linux命令线环境,我觉得这是非常有用的,因为我不是那么热的Bash男孩。
python -c "import os.path; print os.path.isfile('/path_to/file.xxx')"
if os.path.isfile(path_to_file):
try:
open(path_to_file)
pass
except IOError as e:
print "Unable to open file"
提取例外被认为是一个可接受的,和 Pythonic,方法的流量控制在您的程序. 考虑处理错误的文件与 IOErrors. 在这种情况下,一个 IOError 例外将被提取,如果文件存在,但用户没有阅读许可。
来源:使用Python:如何检查是否存在文件
在2016年,最好的方式仍然是使用os.path.isfile:
>>> os.path.isfile('/path/to/some/file.txt')
在Python 3中,您可以使用Pathlib:
import pathlib
path = pathlib.Path('/path/to/some/file.txt')
if path.is_file():
...
推荐文章
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字
- Pipenv:命令未找到
- 根据Pandas中的另一列提取列值
- virtualenv和pyenv是什么关系?