Python `os.path` 模块使用教程
os.path是 Python 标准库中用于处理文件路径的模块支持跨平台路径操作Windows、Linux、macOS。1. 导入模块importos2. 常用路径操作2.1 路径拼接与拆分# os.path.join() - 智能拼接路径path1os.path.join(folder,subfolder,file.txt)print(path1)# folder/subfolder/file.txt (Linux/macOS)# Windows 输出: folder\subfolder\file.txtpath2os.path.join(/home/user,docs,readme.md)print(path2)# /home/user/docs/readme.md# os.path.split() - 拆分目录和文件名dir_part,file_partos.path.split(/home/user/file.txt)print(dir_part)# /home/userprint(file_part)# file.txt# os.path.splitext() - 拆分文件名和扩展名root,extos.path.splitext(document.pdf)print(root)# documentprint(ext)# .pdfroot2,ext2os.path.splitext(archive.tar.gz)print(root2)# archive.tarprint(ext2)# .gz2.2 获取路径组件path/home/user/docs/file.txt# 获取目录名dirnameos.path.dirname(path)print(dirname)# /home/user/docs# 获取文件名包含扩展名basenameos.path.basename(path)print(basename)# file.txt# 获取绝对路径abs_pathos.path.abspath(file.txt)print(abs_path)# /current/working/directory/file.txt# 获取规范化路径消除 . 和 ..norm_pathos.path.normpath(/home/user/../other/./file.txt)print(norm_path)# /home/other/file.txt2.3 路径检查# 假设当前目录下有一个 test.txt 文件和一个 myfolder 文件夹# os.path.exists() - 路径是否存在print(os.path.exists(test.txt))# Trueprint(os.path.exists(notexist.txt))# False# os.path.isfile() - 是否为文件print(os.path.isfile(test.txt))# Trueprint(os.path.isfile(myfolder))# False# os.path.isdir() - 是否为目录print(os.path.isdir(myfolder))# Trueprint(os.path.isdir(test.txt))# False# os.path.isabs() - 是否为绝对路径print(os.path.isabs(/home/file.txt))# Trueprint(os.path.isabs(file.txt))# False# os.path.islink() - 是否为符号链接print(os.path.islink(shortcut))# True/False 取决于是否存在链接2.4 文件大小与时间# 获取文件大小字节sizeos.path.getsize(test.txt)print(size)# 1024 (假设文件大小为1024字节)# 获取各种时间戳importtime atimeos.path.getatime(test.txt)# 最后访问时间mtimeos.path.getmtime(test.txt)# 最后修改时间ctimeos.path.getctime(test.txt)# 创建时间Unix/ 元数据修改时间Windowsprint(time.ctime(atime))# Mon May 18 10:30:00 2026print(time.ctime(mtime))# Mon May 18 10:25:00 2026print(time.ctime(ctime))# Mon May 18 10:20:00 20262.5 路径比较与转换# os.path.commonpath() - 获取公共路径paths[/home/user/docs/file.txt,/home/user/photos/image.jpg]commonos.path.commonpath(paths)print(common)# /home/user# os.path.commonprefix() - 获取公共前缀不保证路径语义prefixos.path.commonprefix([/home/user/a,/home/user/b])print(prefix)# /home/user/# os.path.relpath() - 获取相对路径abs_path/home/user/docs/file.txtrel_pathos.path.relpath(abs_path,start/home)print(rel_path)# user/docs/file.txt# 跨平台路径转换# os.path.expanduser() - 扩展用户目录home_pathos.path.expanduser(~/documents/notes.txt)print(home_path)# /home/username/documents/notes.txt (Linux)# Windows: C:\Users\username\documents\notes.txt# os.path.expandvars() - 扩展环境变量path_with_envos.path.expandvars($HOME/data/file.csv)print(path_with_env)# /home/username/data/file.csv3. 实战示例3.1 遍历目录并处理文件defprocess_directory(dir_path):遍历目录输出所有文件和子目录信息ifnotos.path.exists(dir_path):print(f目录不存在:{dir_path})# 目录不存在: /invalid/pathreturnifnotos.path.isdir(dir_path):print(f不是目录:{dir_path})# 不是目录: test.txtreturnforiteminos.listdir(dir_path):full_pathos.path.join(dir_path,item)ifos.path.isfile(full_path):sizeos.path.getsize(full_path)print(f文件:{item:30}大小:{size:10}字节)# 输出示例: 文件: report.pdf 大小: 2048 字节elifos.path.isdir(full_path):print(f目录:{item:30})# 输出示例: 目录: images# 使用示例# process_directory(/home/user/documents)3.2 安全创建目录defsafe_mkdir(dir_path):安全创建目录如果不存在ifos.path.exists(dir_path):print(f目录已存在:{dir_path})# 目录已存在: /tmp/myapp/datareturnFalseos.makedirs(dir_path,exist_okTrue)# exist_okTrue 不会报错print(f目录创建成功:{dir_path})# 目录创建成功: /tmp/myapp/newfolderreturnTrue# 创建多级目录os.makedirs(parent/child/grandchild,exist_okTrue)print(os.path.exists(parent/child/grandchild))# True3.3 获取文件信息工具函数defget_file_info(file_path):获取文件的详细信息ifnotos.path.isfile(file_path):returnNoneinfo{name:os.path.basename(file_path),dir:os.path.dirname(file_path),size:os.path.getsize(file_path),ext:os.path.splitext(file_path)[1],abspath:os.path.abspath(file_path),}returninfo# 使用示例infoget_file_info(test.txt)ifinfo:print(f文件名:{info[name]})# 文件名: test.txtprint(f所在目录:{info[dir]})# 所在目录: /home/userprint(f大小:{info[size]}字节)# 大小: 1024 字节print(f扩展名:{info[ext]})# 扩展名: .txtprint(f绝对路径:{info[abspath]})# 绝对路径: /home/user/test.txt3.4 查找特定扩展名的文件deffind_files_by_ext(root_dir,extension):递归查找指定扩展名的所有文件matches[]forroot,dirs,filesinos.walk(root_dir):forfileinfiles:iffile.endswith(extension):full_pathos.path.join(root,file)matches.append(full_path)returnmatches# 查找所有 .py 文件py_filesfind_files_by_ext(/home/project,.py)print(f找到{len(py_files)}个 Python 文件)# 找到 42 个 Python 文件forfinpy_files[:3]:# 只显示前3个print(f{f})# 输出示例:# /home/project/main.py# /home/project/utils/helper.py# /home/project/config/settings.py4. 跨平台注意事项# 推荐使用 os.path.join 而不是手动拼接# 不推荐: path folder\\subfolder\\file.txt # 仅Windows# 不推荐: path folder/subfolder/file.txt # 仅Unixpathos.path.join(folder,subfolder,file.txt)# 跨平台 ✅# 处理路径时优先使用 os.path 函数# 而不是手动处理字符串filenamemyfile.txtprint(os.path.splitext(filename)[1])# .txt ✅# 不推荐: filename.split(.)[-1] # 无法处理 .tar.gz 等情况# 获取当前工作目录cwdos.getcwd()print(cwd)# /home/user/project# 改变工作目录os.chdir(/tmp)print(os.getcwd())# /tmp5. 常用函数速查表函数功能示例输出os.path.join(a, b)拼接路径folder/file.txtos.path.split(p)拆分路径(/home, file.txt)os.path.splitext(p)拆分扩展名(file, .txt)os.path.exists(p)判断存在Trueos.path.isfile(p)判断文件Trueos.path.isdir(p)判断目录Falseos.path.getsize(p)获取大小1024os.path.abspath(p)绝对路径/home/user/file.txtos.path.basename(p)文件名file.txtos.path.dirname(p)目录名/home/useros.path.relpath(p)相对路径../other/file.txtos.path.normpath(p)规范化路径/home/user/file.txt这个教程涵盖了os.path的大部分常用功能配合示例输出可以帮助你快速理解和使用。