关于python:0202-Python-读写文件-openossys

6次阅读

共计 878 个字符,预计需要花费 3 分钟才能阅读完成。

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
正文完
 0