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

前言

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

导入包

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

import os
from pathlib import Path

判断路径存在

os方式

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

patlib方式

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

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

os方式

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

pathlib方式

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

获取父路径

os方式

p = "./testPath/testPath2/file.txt"
parent_dir = os.path.dirname(p)
print(parent_dir)

pathlib方式

p = Path("./testPath/testPath2/file.txt")
print(p.parent)

写入读出文件

os方式

with open(p, "w") as f:
    f.write("Hello, World!")

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

pathlib方式

p.write_text("Hello, World!")
content = p.read_text()
print(content)

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

os方式

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方式

p = Path("./testPath/testPath2")
for item in p.iterdir():
    print(item)

获取文件扩展名

os方式

p = "./testPath/testPath2/file.txt"
_, ext = os.path.splitext(p)
print(ext) 

pathlib方式

p = Path("./testPath/testPath2/file.txt")
print(p.suffix) 

获取多个文件扩展名

os方式

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方式

p = Path("./testPath/testPath2/file.tar.gz")
print(p.suffixes)

获取路径的组件

os方式

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方式

p = Path("./testPath/testPath2/file.txt")
print(p.parts)

创建目录

os方式

dir_path = "./testPath/testPath2/file3.txt"
os.makedirs(dir_path, exist_ok=True)

pathlib方式

p = Path("./testPath/testPath2/file3.txt")
p.mkdir(parents=True, exist_ok=True)

删除文件或空目录

os方式

dir_path = "./testPath/testPath2/file3.txt"
os.rmdir(dir_path)

pathlib方式

p = Path("./testPath/testPath2/file3.txt")
p.rmdir()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

艾醒(AiXing-w)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值