python pathlib
在Python中,path通常指的是处理文件和目录路径的模块,这里(li)主要(yao)介绍的是Python标准库中的pathlib模块。pathlib模块提供了一种面(mian)向对象的方(fang)法来处理文件系统路径,使得路径操作更加直观和(he)方便。(图片(pian)来源网络,侵删)
我们需要导入(ru)pathlib模块:

from pathlib import Path
接下来,我们将详细介绍pathlib模块的一些(xie)常用(yong)功能。

1、创建路径对象

使用Path类创建一个路径对象,可以传入一个文件或目录的路径字符串:
p = Path('example.txt')2、获取当前工作目录
使用Path.cwd()方法获取(qu)当前(qian)工作目录:
current_dir = Path.cwd()print(current_dir)
3、改变当前工作目录
使用Path.chdir()方法改变当前工作目录:
new_dir = Path('new_directory')new_dir.mkdir(parents=True, exist_ok=True) # 创建新目录(如果不存在)Path.cwd().chdir(new_dir)4、列出目录内容
使用Path.iterdir()方法(fa)列出(chu)目录中的所有文(wen)件和子目录:
for item in current_dir.iterdir(): print(item)5、检查路径是否存在
使用Path.exists()方法检查路径是否存在:
if p.exists(): print('Path exists')else: print('Path does not exist')6、创建新目录
使用Path.mkdir()方法创建新(xin)目录:
new_dir = Path('new_directory')new_dir.mkdir(parents=True, exist_ok=True)7、删除目录
使用Path.rmdir()方法删除空目录,或(huo)者使用Path.unlink()方法删除文件:
if new_dir.is_dir(): new_dir.rmdir()elif new_dir.is_file(): new_dir.unlink()
8、重命名文件或目录
使用Path.rename()方法(fa)重命名文(wen)件或目录:
old_name = Path('old_name.txt')new_name = Path('new_name.txt')old_name.rename(new_name)9、获取文件扩展名
使用Path.suffix属性获取文件扩展名:
extension = p.suffixprint(extension)
10、拼接路(lu)径
使用Path.joinpath()方(fang)法(fa)拼接路径:
path1 = Path('folder1')path2 = Path('folder2')combined_path = path1.joinpath(path2)print(combined_path)11、相对路径和绝对路(lu)径
使用Path.resolve()方法获取绝对路径,使(shi)用Path.relative_to()方法获取相对路径:
absolute_path = p.resolve()relative_path = current_dir.relative_to(p)print(absolute_path)print(relative_path)以上就是Python中pathlib模块的一些(xie)常用功能的详细介绍,希望对你有所帮助!