If the reason you're checking is so you can do something like if file_exists: open_it()
, it's safer to use a try
around the attempt to open it.
(如果您要检查的原因是可以执行诸如if file_exists: open_it()
,则try
尝试打开它更安全。)
Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it. (检查然后打开可能会导致文件被删除或移动,或者介于检查和尝试打开文件之间。)
If you're not planning to open the file immediately, you can use os.path.isfile
(如果您不打算立即打开文件,则可以使用os.path.isfile
)
Return True
if path is an existing regular file.
(如果path是现有的常规文件,则返回True
。)
import os.path
os.path.isfile(fname)
if you need to be sure it's a file.
(如果您需要确保它是一个文件。)
Starting with Python 3.4, the pathlib
module offers an object-oriented approach (backported to pathlib2
in Python 2.7):
(从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
To check a directory, do:
(要检查目录,请执行以下操作:)
if my_file.is_dir():
# directory exists
To check whether a Path
object exists independently of whether is it a file or directory, use exists()
:
(要检查Path
对象是否独立于文件或目录而exists()
,请使用exists()
:)
if my_file.exists():
# path exists
You can also use resolve(strict=True)
in a try
block:
(您还可以在try
块中使用resolve(strict=True)
:)
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…