如何检查是否存在文件,而不使用试用声明?
当前回答
使用 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
其他回答
它被认为是更好的风格,避免赛车条件。
不要用我的话来支持这个理论,这里有几个:
风格:本课程的“处理异常条件”部分为软件设计(2007) 避免竞赛条件
添加一个更轻微的变化,这在其他答案中不完全反映。
这将处理文件_路径是无或空的字符串的情况。
此分類上一篇
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.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..')
此外, os.access():
if os.access("myfile", os.R_OK):
with open("myfile") as fp:
return fp.read()
是 R_OK, W_OK, 和 X_OK 旗帜测试许可证(doc)。
使用:
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中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字
- Pipenv:命令未找到
- 根据Pandas中的另一列提取列值
- virtualenv和pyenv是什么关系?