如何检查文件是否存在?
时间:2020-03-05 18:58:45 来源:igfitidea点击:
如何不使用try
语句查看文件是否存在?
解决方案
回答
import os.path if os.path.isfile(filepath):
回答
import os os.path.exists(path) # Returns whether the path (directory or file) exists or not os.path.isfile(path) # Returns whether the file exists or not
回答
你有os.path.exists
函数:
import os.path os.path.exists(file_path)
这将为文件和目录返回" True",但我们可以改为使用
os.path.isfile(file_name)
测试它是否是专门的文件。它遵循符号链接。
回答
如果我们要检查的原因是可以执行if file_exists:open_it()
之类的操作,则使用try
尝试打开它会更安全。检查然后打开可能会导致文件被删除或者移动,或者在检查与尝试打开之间之间存在一些风险。
如果我们不打算立即打开文件,则可以使用os.path.isfile
。
Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.
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
要检查路径对象是否独立于文件还是目录,请使用exists():
if my_file.exists(): # path exists
我们也可以在try块中使用resolve():
try: my_abs_path = my_file.resolve() except FileNotFoundError: # doesn't exist else: # exists
回答
另外,os.access()
:
if os.access("myfile", os.R_OK): with open("myfile") as fp: return fp.read()
作为R_OK
,W_OK
和X_OK
的标志来测试权限(文档)。
回答
与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
回答
最好使用try语句。它被认为是更好的风格,避免了比赛条件。
不要相信我。这个理论有很多支持。这是一对:
- 样式:http://allendowney.com/sd/notes/notes11.txt的"处理异常情况"部分
- 避免比赛条件