Python os.path 模块详解:路径拼接、目录操作与批量文件处理

在日常 Python 开发中,文件和目录操作非常频繁。os.path 模块提供了跨平台处理路径的基础功能。本文通过实例说明其核心用法,包括路径拼接、目录创建、文件批量复制与重命名等。

一、路径拼接:os.path.join()

语法:

python 复制代码
os.path.join(path1[, path2[, ...]])

返回值:多个路径拼接后的字符串。

注意:第一个绝对路径之前的参数会被忽略。

示例:

python 复制代码
import os

# 全部相对路径
print(os.path.join('/hello/', 'good/boy/', 'doiido'))
# 输出:/hello/good/boy/doiido

# 中间出现绝对路径
print(os.path.join('/hello/', '/good/boy/', 'doiido'))
# 输出:/good/boy/doiido   (/hello/ 被忽略)

这一特性在拼接用户输入或配置路径时需要留意。

二、分离文件名和路径

使用 os.path.basename 和 os.path.dirname:

python 复制代码
url = 'https://images0.cnblogs.com/i/311516/201403/020013141657112.png'
filename = os.path.basename(url)   # '020013141657112.png'
filepath = os.path.dirname(url)    # 'https://images0.cnblogs.com/i/311516/201403'

使用 os.path.split 同时获得两者:

python 复制代码
parts = os.path.split('/home/user/data/file.txt')
# ('/home/user/data', 'file.txt')

三、安全创建目录

先判断目录是否存在,再创建(支持多级目录):

python 复制代码
def mkdir(path):
    if not os.path.exists(path):
        os.makedirs(path)
        print("--- create new folder %s ---" % path)
    else:
        print("--- already have this folder! ---")

四、创建空文件并自动创建父目录

结合 mkdir 和 os.path.split:

python 复制代码
def create_empty_file(path):
    dir, file = os.path.split(path)
    mkdir(dir)
    open(path, "w").close()

五、批量复制特定类型文件

递归遍历源目录,将指定扩展名的文件复制到目标目录:

python 复制代码
import shutil

def cp_rawdata_snp_2_plate_snp_path(path, new_path):
    for root, dirs, files in os.walk(path):
        for file in files:
            if file[-3:].lower() in ('jpg', 'png'):
                src = os.path.join(root, file)
                dst = os.path.join(new_path, file)
                shutil.copy(src, dst)

六、批量重命名文件

根据映射字典修改文件名:

python 复制代码
def rename_gtc_barcode():
    barcode_map = {"2012333_r1l2": "111-1214-1232"}
    gtc_path = config["dir.gtc_dir_path"]
    for i in os.listdir(gtc_path):
        if not i.endswith(".gtc"):
            continue
        oldname = os.path.join(gtc_path, i)
        newname = os.path.join(gtc_path, barcode_map[i.replace(".gtc", "")] + ".vcf")
        os.rename(oldname, newname)
        print(oldname, '======>', newname)

七、获取当前目录、上级目录等

python 复制代码
import os

# 当前目录
print(os.getcwd())
print(os.path.abspath(os.path.dirname(__file__)))

# 上级目录
print(os.path.abspath(os.path.dirname(os.getcwd())))
print(os.path.abspath(os.path.join(os.getcwd(), "..")))

# 上上级目录
print(os.path.abspath(os.path.join(os.getcwd(), "../..")))

八、常用 os.path 方法速查

方法 说明
os.path.abspath(path) 返回绝对路径
os.path.basename(path) 返回文件名
os.path.dirname(path) 返回目录路径
os.path.exists(path) 路径是否存在
os.path.isfile(path) 是否为文件
os.path.isdir(path) 是否为目录
os.path.getsize(path) 文件大小(字节)
os.path.splitext(path) 分离文件名与扩展名

九、注意事项

  1. 路径分隔符 :Windows 为 \,Linux/macOS 为 /,应始终使用 os.path.join 拼接。
  2. 相对/绝对路径 :不确定时先用 os.path.abspath 转换。
  3. 操作前检查 :删除或修改文件前建议用 os.path.exists 判断。

以上是 os.path 模块在实际开发中的常见用法。掌握这些函数可以有效简化文件系统相关的代码,并提高跨平台兼容性。

相关推荐
Logintern092 小时前
deep agents 多智能体模式——规划与委派
python·langchain
2601_967980113 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值
python·pycharm·办公自动化·数据处理·excel自动计算
databook5 小时前
时间序列预测,模型换了一圈为什么没变好
python·数据分析
reasonsummer6 小时前
【教学类-07-17】20261119大3班破译电话号码HTML实际操作(添加“跳过按钮”和“返回按钮”在底部、增加“自编题目+解题”部分)
python·html
2601_967980119 小时前
Python闭包(Closure)详解
python·作用域·装饰器·函数式编程·闭包
AI创界者9 小时前
ComfyUI 进阶实战:MiniMax-H3 视频人物脸部替换工作流全解析(对比 Face 5.5 实测与避坑指南)
人工智能·python·aigc
承渊政道10 小时前
【Python编程快速上手—让繁琐工作自动化】(模式匹配与正则表达式:从找到一个号码到批量提取信息)
python·正则表达式·pycharm·自动化·模式匹配
JonaHu10 小时前
AceDataCloud Coding Plan 多模型编程:从 Chat Completions 迁移到 Responses API 与工具调用
python·大模型·api·ai编程·acedatacloud
鲸渔10 小时前
【AI Agent系列课程23-Python 基础23】测试入门:为函数写第一个 pytest 用例
开发语言·python·pytest·ai编程
fengkai454511 小时前
Python运维实战
运维·开发语言·python·ssh·sftp·paramiko