如何检查是否存在文件,而不使用试用声明?
当前回答
此外, os.access():
if os.access("myfile", os.R_OK):
with open("myfile") as fp:
return fp.read()
是 R_OK, W_OK, 和 X_OK 旗帜测试许可证(doc)。
其他回答
你可以尝试一下(更安全):
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’)
然后,取决于结果,你的程序可以只是从那里继续运行,或者你可以编码阻止它,如果你愿意。
它被认为是更好的风格,避免赛车条件。
不要用我的话来支持这个理论,这里有几个:
风格:本课程的“处理异常条件”部分为软件设计(2007) 避免竞赛条件
您可以使用 os.listdir 检查文件是否在特定目录中。
import os
if 'file.ext' in os.listdir('dirpath'):
#code
它似乎没有一个有意义的功能区别在尝试/排除和isfile(),所以你应该使用哪一个有意义。
如果你想阅读一个文件,如果它存在,
try:
f = open(filepath)
except IOError:
print 'Oh dear.'
但是,如果你只是想重新命名一个文件,如果它存在,因此不需要打开它,
if os.path.isfile(filepath):
os.rename(filepath, filepath + '.old')
如果你想写到文件,如果它不存在,
# Python 2
if not os.path.isfile(filepath):
f = open(filepath, 'w')
# Python 3: x opens for exclusive creation, failing if the file already exists
try:
f = open(filepath, 'wx')
except IOError:
print 'file already exists'
如果你需要文件锁,那是另一个问题。
您可以使用以下开放方法检查是否存在 + 可阅读的文件:
file = open(inputFile, 'r')
file.close()
推荐文章
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字
- Pipenv:命令未找到
- 根据Pandas中的另一列提取列值
- virtualenv和pyenv是什么关系?