Python高级用法:路径与文件操作(os与pathlib)

路径与文件

前言

在Python中,os模块提供了与操作系统交互的各种功能,包括文件路径的操作。但是,与pathlib相比,os模块通常使用字符串来表示和操作路径,并且它的API更接近于传统的文件系统操作。一般使用pathlib和os相结合的方式对路径进行操作。

导入包

假设我们有以下的路径结构,在本文中将使用这一结构来演示路径和文件操作。

python 复制代码
import os
from pathlib import Path

判断路径存在

os方式

python 复制代码
p = "./testPath/testPath2/file.txt"
if os.path.exists(p):
    print("路径存在")
else:
    print("路径不存在")

patlib方式

python 复制代码
p = Path("./testPath/testPath2/file.txt")
if p.exists():
    print("路径存在")
else:
    print("路径不存在")

判断路径类型(判断文件还是文件夹)

os方式

python 复制代码
p = "./testPath/testPath2/file.txt"
if os.path.isfile(p):
    print("p为文件")
elif os.path.isdir(p):
    print("p为文件夹")
else:
    print("不存在该文件或文件夹")

pathlib方式

python 复制代码
p = Path("./testPath/testPath2/file.txt")
if p.is_file():
    print("p为文件")
elif p.is_dir():
    print("p为文件夹")
else:
    print("不存在该文件或文件夹")

获取父路径

os方式

python 复制代码
p = "./testPath/testPath2/file.txt"
parent_dir = os.path.dirname(p)
print(parent_dir)

pathlib方式

python 复制代码
p = Path("./testPath/testPath2/file.txt")
print(p.parent)

写入读出文件

os方式

python 复制代码
with open(p, "w") as f:
    f.write("Hello, World!")

with open(p, "r") as f:
    content = f.read()
print(content)

pathlib方式

python 复制代码
p.write_text("Hello, World!")
content = p.read_text()
print(content)

获得路径中所有子文件/子文件夹

os方式

python 复制代码
dir_path = "./testPath/testPath2"
for item in os.listdir(dir_path):
    item_path = os.path.join(dir_path, item)
    if os.path.isfile(item_path):
        print(item_path)
    elif os.path.isdir(item_path):
        print(item_path)

pathlib方式

python 复制代码
p = Path("./testPath/testPath2")
for item in p.iterdir():
    print(item)

获取文件扩展名

os方式

python 复制代码
p = "./testPath/testPath2/file.txt"
_, ext = os.path.splitext(p)
print(ext) 

pathlib方式

python 复制代码
p = Path("./testPath/testPath2/file.txt")
print(p.suffix) 

获取多个文件扩展名

os方式

python 复制代码
p = "./testPath/testPath2/file.tar.gz"
base, ext = os.path.splitext(p)
extensions = []
while ext:
    extensions.append(ext)
    base, ext = os.path.splitext(base)

print(extensions[::-1])

pathlib方式

python 复制代码
p = Path("./testPath/testPath2/file.tar.gz")
print(p.suffixes)

获取路径的组件

os方式

python 复制代码
p = "./testPath/testPath2/file.txt"
components = []
head, tail = os.path.split(p)
while head and tail:
    components.append(tail)
    head, tail = os.path.split(head)
components.append(head)  # 添加根目录或最后一个目录部分
components.reverse()
print(components)

pathlib方式

python 复制代码
p = Path("./testPath/testPath2/file.txt")
print(p.parts)

创建目录

os方式

python 复制代码
dir_path = "./testPath/testPath2/file3.txt"
os.makedirs(dir_path, exist_ok=True)

pathlib方式

python 复制代码
p = Path("./testPath/testPath2/file3.txt")
p.mkdir(parents=True, exist_ok=True)

删除文件或空目录

os方式

python 复制代码
dir_path = "./testPath/testPath2/file3.txt"
os.rmdir(dir_path)

pathlib方式

python 复制代码
p = Path("./testPath/testPath2/file3.txt")
p.rmdir()
相关推荐
IVEN_5 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang6 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮6 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling6 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮9 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽10 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers