文章背景: 在读写文件之前,需要判断文件或目录是否存在,不然某些处理方法可能会使程序出错。所以最好在做任何操作之前,先判断文件/目录是否存在。下面介绍两种方法。
1 使用os模块
2 使用pathlib
模块
os
模块 os模块中的os.path.exists(path)
方法用于检验文件/目录是否存在。
Return True
if path refers to an existing path or an open file descriptor. Returns False
for broken symbolic links.
import os
file_path = r"C:\test\test.txt"
print(os.path.exists(file_path))
folder_path = r"C:\test"
print(os.path.exists(folder_path))
上述代码块中,判断文件/目录是否存在,用的是同一个方法,os.path.exists(path)
。对于不带后缀名
的文件,在进行判断时,容易与文件夹相混淆,从而造成误判。
为了避免文件被误判,针对文件,可以使用os.path.isfile(path)
方法。
Return True
if path is an existing
regular file.
import os
file_path = r"C:\test\new.txt"
print(os.path.isfile(file_path))
此外,针对文件夹,还可以使用os.path.isdir(path)
方法。
Return True
if path is an existing
directory.
import os
folder_path = r"C:\test"
print(os.path.isdir(folder_path))
综上,通过os
模块,可以采用如下方法判断文件/目录是否存在。
os.path.exists(path)
判断文件/目录的路径是否存在os.path.isfile(path)
判断文件是否存在os.path.isdir(path)
判断文件夹是否存在pathlib
模块 使用pathlib
模块,需要先使用文件路径来创建path
对象。此路径可以是文件名或目录路径。
from pathlib import Path
file_path = r"C:\test\new.txt"
my_file = Path(file_path)
print(my_file.exists())
folder_path = r"C:\test"
my_folder = Path(folder_path)
print(my_folder.exists())
上述代码块中,判断文件/目录是否存在,用的是同一个方法exists()
。如果文件/目录存在,则返回True
;否则,返回False
。
此外,针对文件,还可以使用is_file()
方法;针对目录,还可以使用is_dir()
方法。文件(或目录)若存在,则返回True
;否则,返回False
。
from pathlib import Path
file_path = r"C:\test\new.txt"
my_file = Path(file_path)
print(my_file.is_file())
folder_path = r"C:\test"
my_folder = Path(folder_path)
print(my_folder.is_dir())
综上,通过pathlib
模块,可以采用如下方法判断文件/目录是否存在。
Path(object_path).exists()
判断文件/目录的路径是否存在Path(file_path).is_file()
判断文件是否存在Path(folder_path).is_dir()
判断文件夹是否存在参考资料:
[1] Python判断文件是否存在的三种方法(https://www.cnblogs.com/jhao/p/7243043.html)
[2] Python 判断文件/目录是否存在(https://www.runoob.com/w3cnote/python-check-whether-a-file-exists.html)
[3] os.path (https://docs.python.org/3/library/os.path.html#module-os.path)
[4] pathlib (https://docs.python.org/3/library/pathlib.html#module-pathlib)