如何使用Python操作路径名?

如何使用Python操作路径名?

在本文中,我们将学习使用 Python 操作路径名。

以下是下面提到的一些不同的示例 -

  • 从文件路径获取主文件名

  • 从文件路径获取目录名

  • 将路径组件连接在一起

  • 扩展用户的主目录

  • 从文件路径中分离文件扩展名

算法(步骤)

以下是执行所需任务所需遵循的算法/步骤。 -

  • 使用 import 关键字导入 os 模块。

  • 创建一个变量来存储输入文件路径。

  • 使用os模块的basename()函数(返回给定文件路径的基本名称)来获取输入文件路径的最后一个组成部分(主文件名)并打印出来。

从文件路径获取主文件名

示例

以下程序使用 os.path.basename() 函数从输入文件返回主文件名 -

# importing os module import os 1. input path of the file inputFilepath = 'C:/Users/cirus/Desktop/tutorialsPoint.pdf' 1. Printing the given input path print("Give Input Path is:",inputFilepath) 1. getting the last component(main file name )of the input file path print("Base Name of the given path is :",os.path.basename(inputFilepath)) 登录后复制