IO小结
文件的输入输出
输入:input
输出:output
涉及到的模块
操作系统交互:os
操作系统路径相关:os.path
os.path.getsize() #获取文件大小
os.path.basename() # 基本路径
os.path.exists() #判断某个文件是否存在
os.path.isdir() #判断是否文件夹
os.path.isfile() #判断是否文件
os.path.join() #拼接路径
解释器交互:sys
模块扩展
Python 中包含了很多模块
- 原生模块:Python官方解释器中就包含的模块
解释器启动时会自动引入一些模块但不是全部模块
类似于列表list、集合set等等可以直接使用
类似于os操作模块,需要import才能使用 - 第三方模块:Python官方解释器中不包含的模块,如果要使用需要单独安装:pip install 模块名称
如:pip install pygame
文件的操作模式
mode操作模式
r:只读
w:只写
a:追加
t:文本
b:二进制
+:读写
文本文件操作
open(file,‘r’)打开一个文件读取文件中的数据
open(file,‘w’)打开一个文件,向文件中写入数据
open(file,‘r’) == open(file,‘rt’)
二进制文件操作
open(file,‘rb’)打开一个二进制文件读取数据
open(file,‘wb’)打开一个二进制文件写入数据
通用操作函数
读取数据:read()
写入数据:write()
文件操作流程
程序中打开文件进行操作之后一定要关闭文件释放资源
with语法:with open (…) as f:
# 写
with open ('text.txt','w') as f1:
f1.write('将此字符串写入文本f1中')
# 读
with open ('text.txt','r') as f1:
print(f1.read())
操作完成之后,会自动关闭文件
Python对象的操作
对象字符串处理操作
- Python对象:字典存储
将字典转换成字符串存储到文件中
users = {'a':'b'}
# 转换成字符串
users_str = str(users)
# 存储
with open('test.txt','w') as f:
f.write(users_str)
- Python对象:读取数据(eval函数)
# 读取文件 (得字符串)
with open('test.txt','r') as f:
users = f.read()
# 字符串转字典
users = eval(users)
JSON模块对象直接操作
- dump(python对象,文件) 存储数据
# 数据
users= {'a','b'}
# 调用json模块直接存储数据
with open('test.txt','w') as f:
json.dump(users,f)
- load(文件) 读取数据
# 调用json模块直接读取数据
with open('text.txt','r') as f:
users = json.load(f)
Python对象的序列化操作
什么是序列化
按照有序的方式整理数据
反序列化:按照定义的有序方式,反向整理数据
pickle序列化模块
- dump(python对象,文件)
(与json一致) - load(文件)
(与json一致)
marshal序列化模块
- dump(python对象,文件)
# 数据准备
s = "字符串"
i = 19
f = 3.1415
b = True
c = 12 + 5j
l = [1,2,3]
d = {'username': 'admin', 'password': '123'}
x = [s, i, f, b, c, l, d]
#1. 存储多个数据到文件中
with open('./data/4.1.dat', 'wb') as file:
# 第一次存储一个数量:有多少个数据存储到了文件中
marshal.dump(len(x), file)
# 存储每个数据
for x1 in x:
marshal.dump(x1, file)
- load(文件)
#2. 将多个数据从文件中依次取出
with open('./data/4.1.dat', 'rb') as file:
n = marshal.load(file)
# 将所有数据依次取出
for x in range(n):
print(marshal.load(file))
shelve序列化模块
- sl = open(file)打开文件进行操作
# 数据准备
users = {'admin': {'username': 'admin', 'password': '123', 'nickname': '大牧'}}
articles = {'标题': {'title': '标题', 'content': '文章内容', 'author': users.get('admin')}}
file = shelve.open('./data/5.1')
# 1. 将多个数据按照key:value的形式存储到文件中
file['users'] = users
file['articles'] = articles
- sl[‘key’] = python对象
# 2. 从文件中根据key读取数据
print(file['users'], type(file['users']))