1frompathlibimportPath23path1 = Path(r"C:\folder\subfolder\myfile.txt")4path2 = Path(r"C:\Myfile.txt")5print(path1.parent)6print(path2.parent) 输出: C:\folder\subfolder C:\ 2、使用os模块的pardir()方法获取父目录 os.pardir是指父目录的常量字符串。对于 Windows 和 POSIX 操作系统,它...
print(Path(__file__).resolve().parent): parent是Path对象的一个属性,它返回表示路径父目录的Path对象。 在这里,resolve()方法首先被调用,以确保我们得到的是绝对路径。然后,parent属性被用来获取这个绝对路径的父目录。 打印这个parent属性会展示脚本所在目录的绝对路径。 总的来说,这些代码展示了如何使用pathlib....
使用parent()和parents(),我们可以获得路径的逻辑父级。 #!/usr/bin/env python3frompathlibimportPathpath=Path('C:/Users/liming/Documents')print(f"The parent directory of {path} is {path.parent}")print(f"The parent of the parent of {path} is {path.parent.parent}")print(f"All the parents...
importos# 获取当前文件路径current_path=os.path.abspath(__file__)# 获取当前文件的上一级目录parent_path=os.path.dirname(current_path)# 获取上一级目录的上一级目录grandparent_path=os.path.dirname(parent_path)print("当前文件的路径:",current_path)print("当前文件的上一级目录:",parent_path)print...
1.Path.parent Path.parent属性返回指定路径的父目录。它会自动去掉路径中的文件名部分。例如,如果我们有一个路径/home/user/test/file.txt,调用Path.parent会返回/home/user/test。 frompathlibimportPath path=Path("/home/user/test/file.txt")parent=path.parentprint(parent)# 输出: /home/user/test ...
Path.mkdir() #创建目录 Path.rename() #重命名路径 Path.rglob() #递归遍历所有子目录的文件 Path.parts #分割路径 类似os.path.split(), 不过返回元组 path.suffix #文件后缀 path.stem #文件名不带后缀 path.name #带后缀的完整文件名 path.parent #路径的上级目录...
parent.parent # 假设脚本位于项目的二级目录下 print(root_path) 在这个例子中,我们假设脚本位于项目的二级目录下。通过调用script_path.parent.parent,我们可以获取到项目的根目录。 无论使用哪种方法,都需要注意项目的目录结构和脚本的位置。在实际开发中,建议将项目根目录路径保存在配置文件中,并在需要时从配置...
os.path.basename PurePath.name 上级目录 os.path.dirname PurePath.parent 同名文件 os.path.samefile Path.samefile 后缀 os.path.splitext PurePath.suffix pathlib 获取文件路径 Path.cwd 获取当前文件夹路径 需注意的是,返回的不是字符串,而是 WindowsPath 对象 代码语言:javascript 代码运行次数:0 运行 AI代...
os.path.join PurePath.joinpath os.path.basename PurePath.name os.path.dirname PurePath.parent os.path.samefile Path.samefile os.path.splitext PurePath.suffix 举4 个例子: # 原来的写法 In : os.path.isdir(os.getcwd()) Out: True # 新的写法 In : Path.cwd().is_dir() Out: True # ...
比如下面这个示例:import os # 创建一个多层级的目录结构,假设从根目录开始这些目录都不存在 multi_dir_path = "parent/child/grandchild"os.makedirs(multi_dir_path)print("多层级目录创建成功!")可以看出,根据实际需求,选择合适的创建目录函数,就能很方便地构建出我们想要的目录结构啦。(...