python-文件操作笔记
基本的文件操作
文件介绍
文件:可以存储在长期存储设备(硬盘、U盘等)上的一段数据即为文件
计算机只认识二进制文件(0、1)
所有的文件在计算器中存储的形式都是二进制0和1,打开文件看到的是文字不是0和1,原因是打开文件的软件会自动将二进制转换为文字
文件的分类(根据能否使用文本软件打开文件):文本文件、二进制文件
文件操作的步骤
打开文件open()
open(file,mode=‘r’,encoding=None)
-file:表示要操作的文件的名字,可以使用绝对路径,也可以使用相对路径
-mode:打开文件的方式,
-r:只读打开,如果文件不存在会报错
-w:只写打开,如果存在会覆盖原文件
-a:追加打开,在文件的末尾写入新的容
-rb:以二进制文件方式打开文件
-wb:以二进制文件方式写入文件
-encoding:编码格式,指二进制数据和汉字转换的规则的
-utf-8(常用):中文编码,将一个汉字转换为3个字节的二进制
-gbk:中文编码,将一个汉字转换为2个字节的二进制
返回值:文件对象,后续对文件的操作,都需要这个文件对象
读写文件
读文件read()
变量=文件对象.read()
返回值:返回读取到文件类容,类型是字符串
写文件write()
文件对象.write()
参数:写入文件的内容,类型字符串
返回值:写入文件中的字符数,字符串的长度 ,一般不关注
文件打开的另一种写法
with open(file,mode,encoding) as 变量: #变量就是文件对象
pass
#使用这种写法打开文件,会自动进行关闭,不用手动书写关闭的代码
#出了with的缩进之后,文件就会自动关闭
#打开文件
f=open('test.txt','w',encoding='utf-8')
#读写文件
f.write('hello world')
#关闭文件
f.close()
#读取文件
f1=open('test.txt','r',encoding='utf-8')
print(f1.read())
f1.close()
#追加写入内容
f3=open('test.txt','a',encoding='utf-8')
f3.write('\nhello world')
f3.close()
print('--------------------------')
#读取文件
with open('test.txt','r',encoding='utf-8') as f1:
print(f1.read())
运行结果:
hello world
--------------------------
hello world
hello world
关闭文件(保存)close()
文件对象.close() #关闭文件,如果是写文件,会自动保存,即将内存中的数据同步到硬盘
按行读取文件:
文件对象.readline() #一次读取一行的内容
'''test,txt
hello world
2hello world'''
#读取文件
with open('test.txt','r',encoding='utf-8') as f1:
print(f1.readline()) #打印结果:hello world
print(f1.readline()) #打印结果:2hello world
模拟读取大文件:
with open('test.txt','r',encoding='utf-8') as f1:
while True:
line=f1.readline()
if not line:
break
print(line)
运行结果:
hello world
2hello world
打开文件的方式
r、w、a称为是文本方式打开,适用于文本文件,会对二进制进行编码转换
rb、wb、ab称为是二进制方式打开,可以打开文本文件和二进制文件,但是二进制文件只能使用二进制方式打开,同时不能传递encoding参数
'''test,txt
hello world
你好中国'''
with open('test.txt','rb') as f1:
print(f1.readline()) #打印结果:b'hello world\r\n'
print(f1.readline()) #打印结果:b'\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xb8\xad\xe5\x9b\xbd'
json文件的操作
json文件的介绍:
json文件的本质也是文本文件,就可以直接使用read和write去进行操作
json文件比较特殊,像python中的字典和列表
json文件使用比较频繁,按照read和write的操作比较麻烦,专门的方法来操作json文件,可以直接得到python中的列表和字典
json文件是一种基于文本,独立于语言的轻量级数据交换格式
-基于文本,文本文件
-独立于语言,不是某一种语言特有的,python\java、c++…
-轻量级,相同的数据量,json文件占用的文件大小相对较小
-数据交换格式,后端服务器和前端页面交换数据使用的格式
在自动化测试中经常用来存放测试数据,文件后缀名为:.json
json语法
json中的数据类型
-对象{} #类比python中字典
-数组[] #类比python中列表
-字符串,必须使用双引号 #类比python中str
-数字类型 #类比python中int float
-bool类型(true\false) #类比python中False
-空值null #类比python中None
json文件,是一个对象或者数组,对象和数组可以相互嵌套
json中的对象,是由键值对组成的,键必须是字符串类型
json中的数据直接使用逗号隔开,最后一个数据后面不能加逗号
json文件的定义:
定义
{
"name":"小明",
"age":18,
"isman":true,
"school":null,
"like":["听歌","吃饭","打豆豆"],
"address":{
"country":"中国",
"city":"广州"
}
}
读取json文件
1.直接使用read读取
with open('one.json','r',encoding='utf-8') as f1:
r=f1.read()
print(type(r))
print(r)
运行结果:
<class 'str'>
{
"name":"小明",
"age":18,
"isman":true,
"school":null,
"like":["听歌","吃饭","打豆豆"],
"address":{
"country":"中国",
"city":"广州"
}
}
2.使用专门的方法读取
2.1导包 import json
2.2json.load(文件对象) #得到的结果是列表或字典
import json
with open('one.json','r',encoding='utf-8') as f1:
r=json.load(f1)
print(type(r))
print(r)
print(r.get('name'))
print(r['like'][0])
print(r['address']['city'])
运行结果:
<class 'dict'>
{'name': '小明', 'age': 18, 'isman': True, 'school': None, 'like': ['听歌', '吃饭', '打豆豆'], 'address': {'country': '中国', 'city': '广州'}}
小明
听歌
广州
练习
创建json文件one.json
[{
"name":"小明",
"age":18,
"sex":"男",
"like":["听歌","吃饭","打豆豆"],
"address":{
"country":"中国",
"city":"广州"
}
},
{
"name":"小红",
"age":17,
"sex":"女",
"like":["听歌","学习","购物"],
"address":{
"country":"中国",
"city":"北京"
}
}]
获取
import json
with open('one.json','r',encoding='utf-8') as f1:
r=json.load(f1)
for i in r:
print(i.get('name'),i.get('age'),i.get('sex'),i.get('address').get('city'))
运行结果:
小明 18 男 广州
小红 17 女 北京
json文件的写入
将python中的列表或者字典转换为json文件
1.导包import json
2.json.dump(python数据,文件对象)
import json
with open('one.json','r',encoding='utf-8') as f1:
global r
r=json.load(f1)
for i in r:
print(i.get('name'),i.get('age'),i.get('sex'),i.get('address').get('city'))
with open('two.json','w',encoding='utf-8') as f1:
json.dump(r,f1,ensure_ascii=False,indent=2) #ensure_ascii控制是否ascii码展示;indent控制缩进,如果这个不写会写入到一行
two.json文件结果:
[
{
"name": "小明",
"age": 18,
"sex": "男",
"like": [
"听歌",
"吃饭",
"打豆豆"
],
"address": {
"country": "中国",
"city": "广州"
}
},
{
"name": "小红",
"age": 17,
"sex": "女",
"like": [
"听歌",
"学习",
"购物"
],
"address": {
"country": "中国",
"city": "北京"
}
}
]