1.新的文件操作库,替代os库
先从pathlib库中导入Path模块
from pathlib import Path
先进行实例化,获取当前文件的绝对路径和相对路径
path = Path(__file__) # 获取当前文件的相对路径
basepath = Path().resolve() # 获取当前文件的绝对路径
Path属性:
path = basepath / "pathlib-课件.py"
print(path) 文件的绝对路径
文件名,后缀名,所有后缀名
# 获取文件全名(包括后缀)
path_filename = path.name
print(path_filename)
# 文件全名(不包括后缀)
path_filename = path.stem
print(path_filename)
# 文件后缀
path_last = path.suffix
# 获取文件的所有后缀名(可能有多个后缀名)
path_all_last = path.suffixes
print(path_last)
取其父路径,路径连接
# 获取文件父路径
path_parent = path.parent
print(path_parent)
# 路径连接
test_path = path_parent / 'test.py'
print(test_path)
# 另一种连接方法,将所有的路径都作为参数放进去
Path(path_parent,)
2、path的方法
判断文件是否存在,创建文件
# 文件路径以及文件创建
# 当文件夹不存在时,直接使用.mkdir(),若该文件夹存在或者创建多级路径会失败,抛出异常
# .mkdir(exist_ok=True)创建单个文件夹,如果存在则忽略,多级同上
# .mkdir(exist_ok=True,parents=True)创建多级路径,存在则忽略
# 判断文件或文件夹是否存在
isfile = test_path.exists()
# 文件路径以及文件创建
# 当文件夹不存在时,直接使用.mkdir(),若该文件夹存在或者创建多级路径会失败,抛出异常
# .mkdir(exist_ok=True)创建单个文件夹,如果存在则忽略,多级同上
# .mkdir(exist_ok=True,parents=True)创建多级路径,存在则忽略
if not path.exists():
path.mkdir() # 创建文件夹,如果存在则抛出异常
path.mkdir(exist_ok=True) # 文件已存在,加上该参数,忽略异常
# 创建多级路径,父级路径不存在则创建.mkdir(exists_ok=True,parents=True)
path = basepath / "a/ b" / "c"
path.mkdir(path.exists(), path)