如何检查文件是否存在?
如何查看文件是否存在,而不使用try
语句?
如果您正在检查的原因是这样你就可以做这样的事情if file_exists: open_it()
它的安全使用try
围绕试图打开它。 检查然后打开文件被删除或移动的风险,或者在您检查和尝试打开文件时出现的风险。
如果你不打算立即打开文件,你可以使用os.path.isfile
如果路径是现有的常规文件,则返回True
。 这遵循符号链接,所以islink()和isfile()对于相同的路径都可以为true。
import os.path
os.path.isfile(fname)
如果你需要确定它是一个文件。
从Python 3.4开始, pathlib
模块提供了一种面向对象的方法(在Python 2.7 pathlib2
移植到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
要检查一个Path
对象是否存在,而不管它是否是文件或目录,请使用exists()
:
if my_file.exists():
# path exists
你也可以在try
块中使用resolve()
:
try:
my_abs_path = my_file.resolve():
except FileNotFoundError:
# doesn't exist
else:
# exists
你有os.path.exists
函数:
import os.path
os.path.exists(file_path)
这会为文件和目录返回True
,但您可以改为使用
os.path.isfile(file_name)
以测试它是否是一个特定的文件。 它遵循符号链接。
与isfile()
不同, exists()
将为目录返回True
。
因此,根据您是否只需要纯文件或目录,您将使用isfile()
或exists()
。 这是一个简单的REPL输出。
>>> print os.path.isfile("/etc/password.txt")
True
>>> print os.path.isfile("/etc")
False
>>> print os.path.isfile("/does/not/exist")
False
>>> print os.path.exists("/etc/password.txt")
True
>>> print os.path.exists("/etc")
True
>>> print os.path.exists("/does/not/exist")
False
链接地址: http://www.djcxy.com/p/101.html
上一篇: How to check whether a file exists?
下一篇: What is the maximum length of a URL in different browsers?