且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Python检查文件是否存在?

更新时间:2022-06-22 23:57:02

如果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


返回 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

要检查目录,请执行:

if my_file.is_dir():
    # directory exists

检查一个 Path $ c>对象是否存在,而不管它是文件还是目录,使用 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