如何使用Python检查文件是否存在? [英] How do I check whether a file exists using Python?
问题描述
如何检查文件是否存在,而不使用 try
声明?
How do I check whether a file exists, without using the try
statement?
推荐答案
如果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.
如果您不打算打开文件立即,您可以使用 os。 path.isfile
$ b
If you're not planning to open the file immediately, you can use 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)
如果您需要确定它是一个文件。
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
要检查目录,请执行:
if my_file.is_dir():
# directory exists
检查一个 Path 对象是否存在,而不管它是文件还是目录,使用
exists )
:
$ b
To check whether a Path
object exists independently of whether is it a file or directory, use exists()
:
if my_file.exists():
# path exists
您也可以使用 resolve()
c $ c> try block:
You can also use resolve()
in a try
block:
try:
my_abs_path = my_file.resolve():
except FileNotFoundError:
# doesn't exist
else:
# exists
这篇关于如何使用Python检查文件是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!