Python如何提取文件路径中的最后三级路径
从文件路径中提取最后三级路径的实现方法
核心思路非常简单:先把路径按分隔符/拆分成独立的目录/文件名列表,取列表的最后三个元素,再用/拼接回路径格式即可。
以下是不同常用场景的实现代码:
Python 实现
基础字符串处理版本:
file_path = "dir1/dir2/dir3/dir4/dir5/file.txt" # 拆分路径同时过滤空字符串,兼容路径开头带/的场景 path_parts = [p for p in file_path.split("/") if p] # 取最后三个元素拼接 new_file_path = "/".join(path_parts[-3:]) print(new_file_path) # 输出:dir4/dir5/file.txt
跨平台适配版本(兼容Windows\分隔符):
import os file_path = "dir1/dir2/dir3/dir4/dir5/file.txt" # 标准化路径后按系统分隔符拆分 path_parts = list(os.path.normpath(file_path).split(os.sep)) new_file_path = os.path.join(*path_parts[-3:])
Shell/Bash 实现
用rev+cut实现最简写法:
filePath="dir1/dir2/dir3/dir4/dir5/file.txt" newFilePath=$(echo "$filePath" | rev | cut -d/ -f1-3 | rev) echo $newFilePath
JavaScript 实现
const filePath = "dir1/dir2/dir3/dir4/dir5/file.txt" const pathParts = filePath.split('/').filter(p => p) const newFilePath = pathParts.slice(-3).join('/') console.log(newFilePath)
- 注意:如果输入路径的层级不足3级,上述方法会直接返回完整路径,不会报错,可根据业务需求提前做长度校验。
内容的提问来源于stack exchange,提问作者Krishna Lakhi
相关产品推荐
相关产品推荐

