如何在Python中检查一个文件是否存在

251 阅读1分钟

在Python中处理文件时,你经常需要在做其他事情之前检查一个文件是否存在,比如从它那里读取或写入它。幸运的是,Python标准库让这一切变得轻而易举。

使用 pathlib.Path.exists(path) 来检查文件和目录。

from pathlib import Path

path_exists = Path.exists("home/dir/file.txt")

if path_exists:
    print("found it!")
else:
    print("not found :(")

请注意 path_existsTrue ,不管这是一个文件还是一个目录,它只检查路径是否存在。

注意:在旧版本的 Python 上,你可能无法访问pathlib 模块。如果是这种情况,你可以使用os.path.exists()

from os.path import exists

path_exists = exists("home/dir/file.txt")

if path_exists:
    print("found it!")
else:
    print("not found :(")

使用pathlib.Path(path).is_file()来检查是否只有文件

from pathlib import Path

file_exists = Path.is_file("home/dir/file.txt")

if file_exists:
    print("found it!")
else:
    print("not found :(")

使用pathlib.Path(path).is_dir()只检查目录

from pathlib import Path

dir_exists = Path.is_dir("home/dir")

if dir_exists:
    print("found it!")
else:
    print("not found :(")

使用pathlib.Path(path).is_symlink()只检查符号链接

符号链接是一个指向文件系统中另一个路径的路径,或者说是一个别名。

from pathlib import Path

symlink_exists = Path.is_dir("home/dir/some_symlink")

if symlink_exists:
    print("found it!")
else:
    print("not found :(")