如何检查是否存在文件,而不使用试用声明?
当前回答
你可以尝试一下(更安全):
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’)
然后,取决于结果,你的程序可以只是从那里继续运行,或者你可以编码阻止它,如果你愿意。
其他回答
您可以使用以下开放方法检查是否存在 + 可阅读的文件:
file = open(inputFile, 'r')
file.close()
您可以使用Python的“OS”图书馆:
>>> import os
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.txt")
True
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.tx")
False
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 错误: 文件不存在
你可以尝试一下(更安全):
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’)
然后,取决于结果,你的程序可以只是从那里继续运行,或者你可以编码阻止它,如果你愿意。
你可以写布莱恩的建议,没有尝试:
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