Python os.path 模块常见用法:路径拼接、目录操作与批量文件处理
作者:AZ-直到世界的尽头
os.path 模块提供了跨平台处理路径的基础功能,本文通过实例说明其核心用法,包括路径拼接、目录创建、文件批量复制与重命名等,感兴趣的朋友一起看看吧
在日常 Python 开发中,文件和目录操作非常频繁。os.path 模块提供了跨平台处理路径的基础功能。本文通过实例说明其核心用法,包括路径拼接、目录创建、文件批量复制与重命名等。
一、路径拼接:os.path.join()
语法:
os.path.join(path1[, path2[, ...]])
返回值:多个路径拼接后的字符串。
注意:第一个绝对路径之前的参数会被忽略。
示例:
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:
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 同时获得两者:
parts = os.path.split('/home/user/data/file.txt')
# ('/home/user/data', 'file.txt')
三、安全创建目录
先判断目录是否存在,再创建(支持多级目录):
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:
def create_empty_file(path):
dir, file = os.path.split(path)
mkdir(dir)
open(path, "w").close()
五、批量复制特定类型文件
递归遍历源目录,将指定扩展名的文件复制到目标目录:
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)六、批量重命名文件
根据映射字典修改文件名:
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)
七、获取当前目录、上级目录等
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) | 分离文件名与扩展名 |
九、注意事项
- 路径分隔符:Windows 为
\,Linux/macOS 为/,应始终使用os.path.join拼接。 - 相对/绝对路径:不确定时先用
os.path.abspath转换。 - 操作前检查:删除或修改文件前建议用
os.path.exists判断。
以上是 os.path 模块在实际开发中的常见用法。掌握这些函数可以有效简化文件系统相关的代码,并提高跨平台兼容性。
到此这篇关于Python os.path 模块常见用法:路径拼接、目录操作与批量文件处理的文章就介绍到这了,更多相关Python os.path 模块用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
