02-02 Python 读写文件 open|os|sys

这篇博客介绍了Python中的open()函数和OS模块的常用技巧。通过with语句读取yaml文件,获取当前文件路径,路径拼接,判断路径是否存在,创建文件夹以及获取工作目录等方法。同时讲解了如何获取绝对路径和文件夹真实路径。这些技巧对于日常的Python文件处理和系统交互非常实用。
摘要由CSDN通过智能技术生成

open

Python open() 函数

常用技巧:

with open(path, encoding="utf-8") as file:
    data = yaml.safe_load(file)
    return data[key]

os

Python OS 文件/目录方法

常用技巧:

import os

# 当前文件所在路径
dir_path = os.path.dirname(os.path.abspath(__file__))

# 拼接路径
case_path = os.path.join(dir_path, "test_case")

# 返回当前工作目录
cur_path = os.getcwd()

# 返回绝对路径
os.path.abspath(path)
os.path.abspath(__file__)  # 包含文件名

# 以数字mode的mode创建一个名为path的文件夹.默认的 mode 是 0777 (八进制)
os.mkdir(path[, mode])

# 如果路径 path 存在,返回 True;如果路径 path 不存在,返回 False
os.path.exists(path)

# 把目录和文件名合成一个路径
os.path.join(path1[, path2[, ...]])

# 返回path的真实路径
os.path.realpath(path)
os.path.realpath(__file__)  # 包含文件名

# 返回文件路径
os.path.dirname(path)
# 结合 os.path.realpath(__file__); os.path.abspath(__file__) 使用
os.path.dirname(os.path.realpath(__file__))  # 不包含文件名
os.path.dirname(os.path.abspath(__file__))  # 不包含文件名

# 判断运行系统内核,win or Linux
os.name

os.path

sys

Python中sys模块

import sys

# 获取运行版本信息,例如python的版本信息
sys.version_info

# 获取运行平台信息,win or Linux
sys.platform
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

肖遥Janic

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

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

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

打赏作者

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

抵扣说明:

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

余额充值