如何检查文件是否存在无例外? [英] How do I check whether a file exists without exceptions?
问题描述
推荐答案
如果要检查的原因是可以执行if file_exists: open_it()
之类的操作,则在尝试打开try
时会更安全.检查然后打开可能会导致文件被删除或移动,或者介于检查和尝试打开文件之间的时间.
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. 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
如果path是现有的常规文件,则返回
True
.这遵循符号链接,因此 islink()和对于同一路径, isfile()可以为true.
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)
如果需要确保它是一个文件.
if you need to be sure it's a file.
从Python 3.4开始, pathlib
模块提供了一种面向对象的方法(在python 2.7中反向移植到pathlib2
):
Starting with Python 3.4, the pathlib
module offers an object-oriented approach (backported to pathlib2
in Python 2.7):
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
要检查Path
对象是否独立于文件或目录而存在,请使用exists()
:
To check whether a Path
object exists independently of whether is it a file or directory, use exists()
:
if my_file.exists():
# path exists
您还可以在try
块中使用resolve(strict=True)
:
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists
这篇关于如何检查文件是否存在无例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!