如何检查是否存在文件,而不使用试用声明?
当前回答
您可以使用以下开放方法检查是否存在 + 可阅读的文件:
file = open(inputFile, 'r')
file.close()
其他回答
它似乎没有一个有意义的功能区别在尝试/排除和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()
使用:
import os
# For testing purposes the arguments defaulted to the current folder and file.
# returns True if file found
def file_exists(FOLDER_PATH='../', FILE_NAME=__file__):
return os.path.isdir(FOLDER_PATH) \
and os.path.isfile(os.path.join(FOLDER_PATH, FILE_NAME))
它基本上是一个文件夹检查,然后使用 os.path.join 使用适当的目录分离器进行文件检查。
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.exist 查看文件和目录:
import os.path
os.path.exists(file_path)
使用 os.path.isfile 仅查看文件(注:以下是符号链接):
os.path.isfile(file_path)