Python `os.path` 模块使用教程
·
os.path 是 Python 标准库中用于处理文件路径的模块,支持跨平台路径操作(Windows、Linux、macOS)。
1. 导入模块
import os
2. 常用路径操作
2.1 路径拼接与拆分
# os.path.join() - 智能拼接路径
path1 = os.path.join('folder', 'subfolder', 'file.txt')
print(path1) # folder/subfolder/file.txt (Linux/macOS)
# Windows 输出: folder\subfolder\file.txt
path2 = os.path.join('/home/user', 'docs', 'readme.md')
print(path2) # /home/user/docs/readme.md
# os.path.split() - 拆分目录和文件名
dir_part, file_part = os.path.split('/home/user/file.txt')
print(dir_part) # /home/user
print(file_part) # file.txt
# os.path.splitext() - 拆分文件名和扩展名
root, ext = os.path.splitext('document.pdf')
print(root) # document
print(ext) # .pdf
root2, ext2 = os.path.splitext('archive.tar.gz')
print(root2) # archive.tar
print(ext2) # .gz
2.2 获取路径组件
path = '/home/user/docs/file.txt'
# 获取目录名
dirname = os.path.dirname(path)
print(dirname) # /home/user/docs
# 获取文件名(包含扩展名)
basename = os.path.basename(path)
print(basename) # file.txt
# 获取绝对路径
abs_path = os.path.abspath('file.txt')
print(abs_path) # /current/working/directory/file.txt
# 获取规范化路径(消除 . 和 ..)
norm_path = os.path.normpath('/home/user/../other/./file.txt')
print(norm_path) # /home/other/file.txt
2.3 路径检查
# 假设当前目录下有一个 test.txt 文件和一个 myfolder 文件夹
# os.path.exists() - 路径是否存在
print(os.path.exists('test.txt')) # True
print(os.path.exists('notexist.txt')) # False
# os.path.isfile() - 是否为文件
print(os.path.isfile('test.txt')) # True
print(os.path.isfile('myfolder')) # False
# os.path.isdir() - 是否为目录
print(os.path.isdir('myfolder')) # True
print(os.path.isdir('test.txt')) # False
# os.path.isabs() - 是否为绝对路径
print(os.path.isabs('/home/file.txt')) # True
print(os.path.isabs('file.txt')) # False
# os.path.islink() - 是否为符号链接
print(os.path.islink('shortcut')) # True/False 取决于是否存在链接
2.4 文件大小与时间
# 获取文件大小(字节)
size = os.path.getsize('test.txt')
print(size) # 1024 (假设文件大小为1024字节)
# 获取各种时间戳
import time
atime = os.path.getatime('test.txt') # 最后访问时间
mtime = os.path.getmtime('test.txt') # 最后修改时间
ctime = os.path.getctime('test.txt') # 创建时间(Unix)/ 元数据修改时间(Windows)
print(time.ctime(atime)) # Mon May 18 10:30:00 2026
print(time.ctime(mtime)) # Mon May 18 10:25:00 2026
print(time.ctime(ctime)) # Mon May 18 10:20:00 2026
2.5 路径比较与转换
# os.path.commonpath() - 获取公共路径
paths = ['/home/user/docs/file.txt', '/home/user/photos/image.jpg']
common = os.path.commonpath(paths)
print(common) # /home/user
# os.path.commonprefix() - 获取公共前缀(不保证路径语义)
prefix = os.path.commonprefix(['/home/user/a', '/home/user/b'])
print(prefix) # /home/user/
# os.path.relpath() - 获取相对路径
abs_path = '/home/user/docs/file.txt'
rel_path = os.path.relpath(abs_path, start='/home')
print(rel_path) # user/docs/file.txt
# 跨平台路径转换
# os.path.expanduser() - 扩展用户目录
home_path = os.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_env = os.path.expandvars('$HOME/data/file.csv')
print(path_with_env) # /home/username/data/file.csv
3. 实战示例
3.1 遍历目录并处理文件
def process_directory(dir_path):
"""遍历目录,输出所有文件和子目录信息"""
if not os.path.exists(dir_path):
print(f"目录不存在: {dir_path}") # 目录不存在: /invalid/path
return
if not os.path.isdir(dir_path):
print(f"不是目录: {dir_path}") # 不是目录: test.txt
return
for item in os.listdir(dir_path):
full_path = os.path.join(dir_path, item)
if os.path.isfile(full_path):
size = os.path.getsize(full_path)
print(f"文件: {item:30} 大小: {size:10} 字节")
# 输出示例: 文件: report.pdf 大小: 2048 字节
elif os.path.isdir(full_path):
print(f"目录: {item:30}")
# 输出示例: 目录: images
# 使用示例
# process_directory('/home/user/documents')
3.2 安全创建目录
def safe_mkdir(dir_path):
"""安全创建目录(如果不存在)"""
if os.path.exists(dir_path):
print(f"目录已存在: {dir_path}") # 目录已存在: /tmp/myapp/data
return False
os.makedirs(dir_path, exist_ok=True) # exist_ok=True 不会报错
print(f"目录创建成功: {dir_path}") # 目录创建成功: /tmp/myapp/newfolder
return True
# 创建多级目录
os.makedirs('parent/child/grandchild', exist_ok=True)
print(os.path.exists('parent/child/grandchild')) # True
3.3 获取文件信息工具函数
def get_file_info(file_path):
"""获取文件的详细信息"""
if not os.path.isfile(file_path):
return None
info = {
'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),
}
return info
# 使用示例
info = get_file_info('test.txt')
if info:
print(f"文件名: {info['name']}") # 文件名: test.txt
print(f"所在目录: {info['dir']}") # 所在目录: /home/user
print(f"大小: {info['size']} 字节") # 大小: 1024 字节
print(f"扩展名: {info['ext']}") # 扩展名: .txt
print(f"绝对路径: {info['abspath']}") # 绝对路径: /home/user/test.txt
3.4 查找特定扩展名的文件
def find_files_by_ext(root_dir, extension):
"""递归查找指定扩展名的所有文件"""
matches = []
for root, dirs, files in os.walk(root_dir):
for file in files:
if file.endswith(extension):
full_path = os.path.join(root, file)
matches.append(full_path)
return matches
# 查找所有 .py 文件
py_files = find_files_by_ext('/home/project', '.py')
print(f"找到 {len(py_files)} 个 Python 文件") # 找到 42 个 Python 文件
for f in py_files[:3]: # 只显示前3个
print(f" {f}")
# 输出示例:
# /home/project/main.py
# /home/project/utils/helper.py
# /home/project/config/settings.py
4. 跨平台注意事项
# 推荐使用 os.path.join 而不是手动拼接
# 不推荐: path = 'folder\\subfolder\\file.txt' # 仅Windows
# 不推荐: path = 'folder/subfolder/file.txt' # 仅Unix
path = os.path.join('folder', 'subfolder', 'file.txt') # 跨平台 ✅
# 处理路径时优先使用 os.path 函数
# 而不是手动处理字符串
filename = 'myfile.txt'
print(os.path.splitext(filename)[1]) # .txt ✅
# 不推荐: filename.split('.')[-1] # 无法处理 .tar.gz 等情况
# 获取当前工作目录
cwd = os.getcwd()
print(cwd) # /home/user/project
# 改变工作目录
os.chdir('/tmp')
print(os.getcwd()) # /tmp
5. 常用函数速查表
| 函数 | 功能 | 示例输出 |
|---|---|---|
os.path.join(a, b) |
拼接路径 | 'folder/file.txt' |
os.path.split(p) |
拆分路径 | ('/home', 'file.txt') |
os.path.splitext(p) |
拆分扩展名 | ('file', '.txt') |
os.path.exists(p) |
判断存在 | True |
os.path.isfile(p) |
判断文件 | True |
os.path.isdir(p) |
判断目录 | False |
os.path.getsize(p) |
获取大小 | 1024 |
os.path.abspath(p) |
绝对路径 | /home/user/file.txt |
os.path.basename(p) |
文件名 | 'file.txt' |
os.path.dirname(p) |
目录名 | '/home/user' |
os.path.relpath(p) |
相对路径 | '../other/file.txt' |
os.path.normpath(p) |
规范化路径 | /home/user/file.txt |
这个教程涵盖了 os.path 的大部分常用功能,配合示例输出可以帮助你快速理解和使用。
更多推荐

所有评论(0)