如何检查是否存在文件,而不使用试用声明?


当前回答

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:如何检查是否存在文件

其他回答

它被认为是更好的风格,避免赛车条件。

不要用我的话来支持这个理论,这里有几个:

风格:本课程的“处理异常条件”部分为软件设计(2007) 避免竞赛条件

如果文件是要打开的,您可以使用以下技术之一:

with open('somefile', 'xt') as f: # Using the x-flag, Python 3.3 and above
    f.write('Hello\n')

if not os.path.exists('somefile'): 
    with open('somefile', 'wt') as f:
        f.write("Hello\n")
else:
    print('File already exists!')

注意:此查找一个文件或指定的名称的目录。

import os

if os.path.isfile(filepath):
   print("File exists")

你可以尝试一下(更安全):

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’)

然后,取决于结果,你的程序可以只是从那里继续运行,或者你可以编码阻止它,如果你愿意。

使用 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