11.1 Python文件读写
-
open()函数
-
文件的读取与写入
11.2 Python读写文本文件
-
文件写入
-
文件读取
- 格式化的输入输出,使用%來格式化字串
11.3 Python读写二进制文件
- 默认都是读取文本文件,并且是ASCII编码的文本文件。 要读取二进制文件,比如图片、视频等等,用'rb'模式打开文件即可。
- 要读取非ASCII编码的文本文件,就必须以二进制模式打开,再解码。 比如GBK编码的文件。
11.4 Python读写json文件
json文件格式一般有两种:
- 第一种:每行一个json类似于以下这种形式:这种json格式是每一行是一个json,行与行之间没有关联。
- 第二种:一个文件写成一个大的json:这种格式每条记录之间用,连接。
- 读取json文件,利用json.load函数
11.5 实验
11.5.1文本
11.5.1.1写数据
In:
# wf = open("output.txt",'w',encoding='utf-8')
In:
txt = '''
我来到山西五台山
我来到北京天安门'''
In:
txt2 = '''
I am here'''
In:
wf.write(txt2)
out:
10
In:
# wf.close
out:
<function TextIOWrapper.close()>
In:
txt2
out:
'\nI am here'
In:
#自动关闭
with open("output2.txt",'w',encoding='utf-8') as f:
f.write(txt2)
In:
txt
out:
'\n我来到山西五台山\n我来到北京天安门'
In:
with open("output.txt",'w',encoding='utf-8') as f:
f.write(txt)
11.5.1.2 读数据
In:
with open("output.txt","r",encoding='utf-8') as f:
rtxt = f.read()
In:
type(rtxt)
out:
str
In:
rtxt.splitlines()
out:
['', '我来到山西五台山', '我来到北京天安门']
In:
with open("output.txt","r",encoding='utf-8') as f:
rtxts = f.readlines()
In:
type(rtxts)
out:
list
In:
for txt in rtxts:
# print(txt)
print(txt.strip())
out:
我来到山西五台山
我来到北京天安门
In:
newlist = [txt.strip() for txt in rtxts if len(txt.strip()) > 0]
newlist
out:
['我来到山西五台山', '我来到北京天安门']
11.5.2 JSON
In:
import json
In:
#读取用 json.loads
with open("poetry_10316.json",'r',encoding='utf-8') as f:
fred = f.read()
In:
poe = json.loads(fred)
In:
poe['name']
out:
'留上李右相(一作奉赠李右相林甫)'
In:
[key for key in poe.keys()]
out:
['id', 'star', 'name', 'dynasty', 'content', 'poet', 'tags']
In:
lis1 = []
for i in range(10):
dic1 = {}
dic1['id'] = i
dic1['name'] = 'sz'
lis1.append(dic1)
lis1
out:
[{'id': 0, 'name': 'sz'},
{'id': 1, 'name': 'sz'},
{'id': 2, 'name': 'sz'},
{'id': 3, 'name': 'sz'},
{'id': 4, 'name': 'sz'},
{'id': 5, 'name': 'sz'},
{'id': 6, 'name': 'sz'},
{'id': 7, 'name': 'sz'},
{'id': 8, 'name': 'sz'},
{'id': 9, 'name': 'sz'}]
In:
with open("output.json","w",encoding='utf-8') as f:
f.write(json.dumps(lis1))