MEMOO
MEMOO
Published on 2025-04-21 / 5 Visits
0
0

Python检测文件是否存在

摘要:在本教程中,你将学习如何使用 os.path.exists()pathlib.is_file() 函数来检查文件是否存在。

在处理文件时,你通常希望在执行其他操作(如从文件读取数据或向文件写入数据)之前检查文件是否存在。

要检查文件是否存在,可以使用 os.path 模块中的 exists() 函数:

from os.path import exists

file_exists = exists(path_to_file)

或者,你可以使用 pathlib 模块中 Path 类的 is_file() 方法:

from pathlib import Path

path = Path(path_to_file)

path.is_file()

使用 os.path.exists() 函数检查文件是否存在

要检查文件是否存在,可以将文件路径传递给 os.path 标准库中的 exists() 函数。

首先,导入 os.path 标准库:

import os.path

第二,调用 exists() 函数:

os.path.exists(path_to_file)

如果文件存在exists() 函数将返回 True。否则,它返回 False

如果文件与程序位于同一文件夹中,则 path_to_file 仅为文件名。

然而,如果不是这种情况,你需要传递文件的完整路径。例如:

/path/to/filename

即使在 Windows 上运行程序,你也应该使用正斜杠 /) 来分隔路径。这样在 Windows、macOS 和 Linux 上都能正常工作。

以下示例使用 exists() 函数检查 readme.txt 文件是否存在于与程序相同的文件夹中:

import os.path

file_exists = os.path.exists('readme.txt')

print(file_exists)

如果 readme.txt 文件存在,你将看到以下输出:

True

否则,你将在屏幕上看到 False

False

为了让对 exists() 函数的调用更简洁、更直观,你可以导入该函数并将其重命名为 file_exists() 函数,如下所示:

from os.path import exists as file_exists

file_exists('readme.txt')

使用 pathlib 模块检查文件是否存在

pathlib 模块允许你使用面向对象的方法来操作文件和目录。如果你不熟悉面向对象编程,可以查看 Python 的面向对象编程部分。

Python 从 3.4 版本开始引入了 pathlib 模块。因此,你应该使用 Python 3.4 或更高版本才能使用该模块。

首先,从 pathlib 模块中导入 Path 类:

from pathlib import Path

然后,实例化一个 Path 类的新对象,并使用你想要检查其是否存在的文件路径来初始化它:

path = Path(path_to_file)

最后,使用 is_file() 方法检查文件是否存在:

path.is_file()

如果文件不存在is_file() 方法将返回 False。否则,它返回 True

以下示例展示了如何使用 pathlib 模块中的 Path 类来检查 readme.txt 文件是否存在于程序的同一文件夹中:

from pathlib import Path

path_to_file = 'readme.txt'
path = Path(path_to_file)

if path.is_file():
    print(f'The file {path_to_file} exists')
else:
    print(f'The file {path_to_file} does not exist')

如果 readme.txt 文件存在,你将看到以下输出:

The file readme.txt exists

总结

  • 使用 os.path.exists() 函数或 Path.is_file() 方法来检查文件是否存在



Comment