本篇博客整理了Python3对文件的一些实用操作方法

一、 python3从给定的文件路径的字符串中获取文件名

  • 方法一
import ntpath

src_file_path = r'C:\ZCodes\pro_22\src\a.txt'
print(ntpath.basename(src_file_path)) # 输出:a.txt -------- 取带后缀的文件名
print(ntpath.dirname(src_file_path)) # 输出:C:\ZCodes\pro_22\src ------------ 取文件的所在的目录路径
  • 方法二
import os

src_file_path = r'C:\ZCodes\pro_22\src\a.txt'
print(os.path.split(src_file_path)) # 输出:('C:\ZCodes\pro_22\src', 'a.txt') 元组
print(os.path.split(src_file_path)[1]) # 输出:a.txt -------- 取带后缀的文件名
print(os.path.split(src_file_path)[0]) # 输出:C:\ZCodes\pro_22\src ------------ 取文件的所在的目录路径

二、python3从给定的文件路径的字符串中获取文件名「无拓展名」

import os

src_file_path = r'C:\ZCodes\pro_22\src\a.txt'
print(os.path.splitext(src_file_path)) # 输出:('C:\ZCodes\pro_22\src\a', '.txt') 
print(os.path.splitext(src_file_path)[1]) # 输出:.txt ------- 取后缀
temp_src_file_path = os.path.splitext(src_file_path)
print(os.path.split(temp_src_file_path)) # 输出:('C:\ZCodes\pro_22\src', 'a') 
print(os.path.split(temp_src_file_path)[1]) # 输出:a -------- 取不带后缀的文件名
print(os.path.split(temp_src_file_path)[0]) # 输出:C:\ZCodes\pro_22\src ------------- 取文件的所在的目录路径