如何检查是否存在文件,而不使用试用声明?
当前回答
虽然我总是建议使用尝试和除陈述,这里有几个选项为您(我的个人喜爱是使用os.access):
尝试打开文件:打开文件将始终确认文件的存在. 你可以这样做一个函数: def File_Existence(filepath): f = open(filepath) return True 如果它是错误的,它将停止执行与未经处理的 IOError 或 OSError 在后续版本的 Python. 要捕获例外,你必须使用一个尝试,除了条款。
我还应该提到,有两种方式,你将无法验证一个文件的存在. 无论问题将被拒绝许可或没有这样的文件或目录. 如果你抓住一个IOError,设置IOError为e(如我的第一个选项),然后输入打印(e.args),以便你可以希望确定你的问题. 我希望它有助于! :)
其他回答
如果你正在检查的原因是,所以你可以做一些类似的文件_存在: open_it(),它更安全地使用一个尝试周围试图打开它。
如果您不打算立即打开文件,您可以使用 os.path.isfile。
如果路径是现有常规文件,则返回是真实的,这跟随了象征性链接,因此 islink() 和 isfile() 都可以对同一条路径是真实的。
import os.path
os.path.isfile(fname)
如果你需要确保它是一个文件。
从 Python 3.4 开始,Pathlib 模块提供一个以对象为导向的方法(在 Python 2.7 中返回Pathlib2):
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists
要查看一个目录,请:
if my_file.is_dir():
# directory exists
要检查路径对象是否存在,无论它是否是一个文件或目录,使用存在():
if my_file.exists():
# path exists
您也可以在尝试区块中使用 resolve(strict=True):
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists
使用 os.path.exist 查看文件和目录:
import os.path
os.path.exists(file_path)
使用 os.path.isfile 仅查看文件(注:以下是符号链接):
os.path.isfile(file_path)
import os.path
def isReadableFile(file_path, file_name):
full_path = file_path + "/" + file_name
try:
if not os.path.exists(file_path):
print "File path is invalid."
return False
elif not os.path.isfile(full_path):
print "File does not exist."
return False
elif not os.access(full_path, os.R_OK):
print "File cannot be read."
return False
else:
print "File can be read."
return True
except IOError as ex:
print "I/O error({0}): {1}".format(ex.errno, ex.strerror)
except Error as ex:
print "Error({0}): {1}".format(ex.errno, ex.strerror)
return False
#------------------------------------------------------
path = "/usr/khaled/documents/puzzles"
fileName = "puzzle_1.txt"
isReadableFile(path, fileName)
使用:
import os
#Your path here e.g. "C:\Program Files\text.txt"
#For access purposes: "C:\\Program Files\\text.txt"
if os.path.exists("C:\..."):
print "File found!"
else:
print "File not found!"
进口 OS 使您更容易与您的操作系统一起导航和执行标准操作。
请参见《如何检查没有例外的文件是否存在》。
如果您需要高级操作,请使用Shutil。
Python 3.4+ 有一个以对象为导向的路径模块: pathlib. 使用这个新模块,您可以检查是否存在这样的文件:
import pathlib
p = pathlib.Path('path/to/file')
if p.is_file(): # or p.is_dir() to see if it is a directory
# do stuff
在打开文件时,您仍然可以(通常应该)使用尝试/排除区块:
try:
with p.open() as f:
# do awesome stuff
except OSError:
print('Well darn.')
pathlib 模块有很多很好的东西在它:方便的旋转,检查文件的所有者,更容易的路径加入,等等,值得检查。 如果你在更老的 Python (版本 2.6 或更晚),你仍然可以安装 pathlib 带 pip:
# installs pathlib2 on older Python versions
# the original third-party module, pathlib, is no longer maintained.
pip install pathlib2
然后将其输入如下:
# Older Python versions
import pathlib2 as pathlib