如何检查是否存在文件,而不使用试用声明?
当前回答
查看文件或目录存在
你可以遵循这三种方式:
使用 isfile( )
注意1: os.path.isfile 仅用于文件
import os.path
os.path.isfile(filename) # True if file exists
os.path.isfile(dirname) # False if directory exists
二、使用存在
注意2: os.path.exists 用于文件和目录
import os.path
os.path.exists(filename) # True if file exists
os.path.exists(dirname) # True if directory exists
pathlib.Path 方法(包含在 Python 3+ 中,可与 Python 2 的 pip 安装)
from pathlib import Path
Path(filename).exists()
其他回答
使用 os.path.exists() 查看是否存在文件:
def fileAtLocation(filename,path):
return os.path.exists(path + filename)
filename="dummy.txt"
path = "/home/ie/SachinSaga/scripts/subscription_unit_reader_file/"
if fileAtLocation(filename,path):
print('file found at location..')
else:
print('file not found at location..')
你可以尝试一下(更安全):
try:
# http://effbot.org/zone/python-with-statement.htm
# 'with' is safer to open a file
with open('whatever.txt') as fh:
# Do something with 'fh'
except IOError as e:
print("({})".format(e))
奥普特将是:
(没有此类文件或目录:‘whatever.txt’)
然后,取决于结果,你的程序可以只是从那里继续运行,或者你可以编码阻止它,如果你愿意。
使用:
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。
使用 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
你可以写布莱恩的建议,没有尝试:
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中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字
- Pipenv:命令未找到
- 根据Pandas中的另一列提取列值
- virtualenv和pyenv是什么关系?