Python3常用的文件操作总结
本篇博客整理了Python3对文件的一些实用操作方法
一、 python3从给定的文件路径的字符串中获取文件名
-
方法一
import ntpath src_file_path = rC:Codespro_22srca.txt print(ntpath.basename(src_file_path)) # 输出:a.txt -------- 取带后缀的文件名 print(ntpath.dirname(src_file_path)) # 输出:C:Codespro_22src ------------ 取文件的所在的目录路径
-
方法二
import os src_file_path = rC:Codespro_22srca.txt print(os.path.split(src_file_path)) # 输出:(C:Codespro_22src, a.txt) 元组 print(os.path.split(src_file_path)[1]) # 输出:a.txt -------- 取带后缀的文件名 print(os.path.split(src_file_path)[0]) # 输出:C:Codespro_22src ------------ 取文件的所在的目录路径
二、python3从给定的文件路径的字符串中获取文件名「无拓展名」
import os src_file_path = rC:Codespro_22srca.txt print(os.path.splitext(src_file_path)) # 输出:(C:Codespro_22srca, .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:Codespro_22src, a) print(os.path.split(temp_src_file_path)[1]) # 输出:a -------- 取不带后缀的文件名 print(os.path.split(temp_src_file_path)[0]) # 输出:C:Codespro_22src ------------- 取文件的所在的目录路径