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


当前回答

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

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

风格:本课程的“处理异常条件”部分为软件设计(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!')

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

您可以使用以下开放方法检查是否存在 + 可阅读的文件:

file = open(inputFile, 'r')
file.close()

exist() and is_file() 对“路”对象的方法可以用来检查是否有一个特定的路径存在并是一个文件。

Python 3 程序检查是否存在文件:

# File name:  check-if-file-exists.py

from pathlib import Path

filePath = Path(input("Enter path of the file to be found: "))

if filePath.exists() and filePath.is_file():
    print("Success: File exists")
else:
    print("Error: File does not exist")

出口:

$ python3 check-if-file-exists.py 输入文件的路径可以找到: /Users/macuser1/stack-overflow/index.html 成功: 文件存在 $ python3 check-if-file-exists.py 输入文件的路径可以找到: hghjg jghj 错误: 文件不存在

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

虽然我总是建议使用尝试和除陈述,这里有几个选项为您(我的个人喜爱是使用os.access):

尝试打开文件:打开文件将始终确认文件的存在. 你可以这样做一个函数: def File_Existence(filepath): f = open(filepath) return True 如果它是错误的,它将停止执行与未经处理的 IOError 或 OSError 在后续版本的 Python. 要捕获例外,你必须使用一个尝试,除了条款。

我还应该提到,有两种方式,你将无法验证一个文件的存在. 无论问题将被拒绝许可或没有这样的文件或目录. 如果你抓住一个IOError,设置IOError为e(如我的第一个选项),然后输入打印(e.args),以便你可以希望确定你的问题. 我希望它有助于! :)