筱团Blog筱团のBlog

python 高级用法 -- IO编程

筱团·2022-08-02 11:20·33 次阅读

python 高级用法 -- IO编程

Prerequisite#

参考文章:廖雪峰的文章

文件读写#

只记录平时用的比较多的

Copy
# wb / rb 二进制形式写入 / 读取 # b'\xff\xd8\xff\xe1\x00\x18Exif\x00\x00...' # 十六进制表示的字节 # a 追加形式写入 # open 函数中的参数 # encoding='gbk' 编码 # errors='ignore' 忽略文件中非法编码的字符 # 几种常用的读写方法 # read() 一次性读取文件的全部内容 # read(size) 每次最多读取 size 个字节的内容 # readline() 每次读取一行内容 # readlines() 一次读取所有内容并按行返回 list # 自动调用 close 函数的读取方法 with open('file', 'r') as f: print(f.read()) # 读取每一行 f = open('file', 'r') for line in f.readlines(): print(line.strip()) # 把末尾的'\n'删掉 f.close()

StringIO 和 BytesIO#

从内存中读写数据,但对我没用,不记(硬气)

操作文件和目录#

关于更多的 OS 标准库用法:Python 标准库之 os 模块详解

Copy
import os import shutil os.name # 操作系统类型 os.uname() # 获取详细的系统信息(Windows 不支持) os.environ # 在操作系统中定义的环境变量 os.environ.get('PATH') # 获取某个环境变量的值 os.path.abspath('.') # 查看当前目录的绝对路径 '/Users/michael' os.mkdir('/Users/michael/testdir') # 然后创建一个目录 os.rmdir('/Users/michael/testdir') # 删掉一个目录 # 想要查看当前操作系统的拼接方式 os.path.join(os.path.abspath('.'), 'temp') 'C:\\Users\\xxx\\temp' # 想要合并 / 拆分路径 os.path.join() / os.path.split() os.rename('test.txt', 'test.py') # 文件重命名 os.remove('test.py') # 删掉文件 shutil.copyfile() # 复制文件 # 列出当前目录下的所有目录 [x for x in os.listdir('.') if os.path.isdir(x)] # 列出所有的 .py 文件 [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']

序列化#

序列化含义:把变量从内存中变成可存储或传输的过程
反序列化含义:把变量内容从序列化的对象重新读到内存里

简单来说:就是把变量储存进一个文件中,然后全平台操作系统,都可以无障碍读取这个文件;与编码的区别就是,编码还要注意格式,且储存的是字符(或者是代码本身),而不是这段数据(内存)
PS:序列化在 Python 中叫 pickling,在其他语言中也被称之为 serialization,marshalling,flattening 等等,都是一个意思

Copy
import pickle import json d = dict(name='Bob', age=20, score=88) f = open('dump.txt', 'wb') pickle.dump(d, f) # 把一个对象序列化并写入文件 f.close() f = open('dump.txt', 'rb') d = pickle.load(f) # 从文件中反序列化出对象 f.close() # 针对 JSON(注意数据的变化) d = dict(name='Bob', age=20, score=88) print(json.dumps(d)) # 序列化成 JSON '{"age": 20, "score": 88, "name": "Bob"}' json_str = '{"age": 20, "score": 88, "name": "Bob"}' print(json.loads(json_str)) # 反序列化成 Python 对象 {'age': 20, 'score': 88, 'name': 'Bob'} # 针对类 class Student(object): def __init__(self, name, age, score): self.name = name self.age = age self.score = score def student2dict(std): return { 'name': std.name, 'age': std.age, 'score': std.score } def dict2student(d): return Student(d['name'], d['age'], d['score']) s = Student('Bob', 20, 88) print(json.dumps(s, default=student2dict)) # 序列化成 Python 对象 print(json.dumps(s, default=lambda obj: obj.__dict__)) # 类自带的字典,序列化成 Python 对象 {"age": 20, "name": "Bob", "score": 88} json_str = '{"age": 20, "score": 88, "name": "Bob"}' print(json.loads(json_str, object_hook=dict2student)) # 反序列化成类的实例 <__main__.Student object at 0x10cd3c190> # PS:写个好玩的,把类的实例序列化成 Python 对象,再序列化成 JSON print(json.dumps(json.dumps(s, default=student2dict))) "{\"name\": \"Bob\", \"age\": 20, \"score\": 88}"
posted @   筱团  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示
目录