文件操作
文件定义
普通文件的操作
打开和关闭文件
gbk:将一个汉字转换为2个字节二进制
utf-8:将一个汉字转换为3个字节二进制
返回值:返回的是 文件对象 也是python内部定义的一个类 操作这个文件对象
读和写文件
写文件:向文件中写入指定的内容
前提 打开方式为 w / a
f = open('a.txt','w',encoding='utf-8')
f.write('好好学习')
#文件不存在 直接创建文件
#文件存在,会覆盖源文件
f.close()
#要换行 得\n 否则是连着的
f = open('a.txt','w',encoding='utf-8')
f.write('好好学习\n')
f.write('天天学习\n')
f.close()
f = open('b.txt','r',encoding='utf-8')
# r方式打开文件 如果文件不存在 代码会报错
buf = f.read()
print(buf)
f.close()
with open
with open('a.txt','a',encoding='utf-8') as f:
f.write('good good study')
# a方式打开文件,文件不存在会创建文件,文件存在,在文件的末尾写入内容
# 追加
循环读:
# 默认不写 为只读 r
with open('b.txt',encoding='utf-8') as f:
buf = f.readline()
print(buf)
print(f.readline())
with open('b.txt',encoding='utf-8') as f:
for i in f:
print(i,end='')
print()
# read() 和readline() 读到文件末尾,返回一个空字符串
with open('b.txt',encoding='utf-8') as f:
while True:
buf = f.readline()
# if len(buf) == 0:
if not buf:
break
else:
print(buf,end = '')
在容器中 容器为空 即容器中的数据的个数为0 表示False 其余为True
json文件的操作
json处理起来方便
{
"name": "小明",
"age": 18,
"isMen": true,
"like": ["singsong","shopping"],
"address": {
"country": "中国",
"city": "上海"
}
}
import json
with open('info.json',encoding='utf-8') as f:
result = json.load(f)
print(type(result)) # <class 'dict'>
print(result.get('name'))
print(result.get('address').get('city'))
读文件
只能有一个对象,加数组
import json
with open('info1.json',encoding='utf-8') as f:
list = json.load(f)
for l in list:
print(l.get('age'))
print(l.get('address').get("city"))
[(),(),()] 自动化参数化需要的数据格式
import json
def read_data():
list = []
with open('info2.json', encoding='utf-8') as f:
dic = json.load(f)
for i in dic:
k = ()
k += (i.get("username"), i.get("password"), i.get("expect"))
# k = (i.get("username"), i.get("password"), i.get("expect")) 直接这样
# list.append(k)
list.append(k)
return list
# [('admin', 123456, '登录成功'), ('root', 123456, '登录失败'), ('admin', 123123, '登录失败')]
import json
my_list = [('admin', 123456, '登录成功'), ('root', 123456, '登录失败'), ('admin', 123123, '登录失败')]
with open('info3.json','w',encoding='utf-8') as f:
# json.dump(my_list,f,ensure_ascii=False) # 直接显示中文,不以ASCII码显示
# 显示缩进
json.dump(my_list, f, ensure_ascii=False,indent=2)
异常处理
异常类型 异常信息
try:
num = input()
num = int(num)
print(num)
except:
print('数字!!!')
print("yep yep") # 后续代码继续执行
try:
num = input()
num = int(num)
print(num)
except ValueError: # 只能捕获ValueError类型及其子类的异常
print('数字!!!')
print("yep yep") # 后续代码继续执行
try:
num = input()
num = int(num)
print(num)
a = 10 / num
except ValueError: # 只能捕获ValueError类型及其子类的异常
print('数字!!!')
print("yep yep") # 后续代码继续执行
try:
num = input()
num = int(num)
print(num)
a = 10 / num
except ValueError: # 只能捕获ValueError类型及其子类的异常
print('数字!!!')
except ZeroDivisionError:
print('除数不能为0')
print("yep yep") # 后续代码继续执行
异常完整版本:
try:
num = input()
num = int(num)
print(num)
a = 10 / num
except Exception as e:
print(f'错误信息为{e}')
else:
print(f'没有异常会输出')
finally:
print('不管有没有异常 都会执行')
二进制方式打开文件 不能指定编码方式
f = open('test.txt','w',encoding='utf-8')
f.write("wow,so beautiful!")
f.close()
f = open('test.txt','r',encoding='utf-8')
data = f.read()
print(data)
f.close()
with open('a.txt','w',encoding='utf-8') as f:
f.write('张三,李四,王五')
with open('a.txt','r',encoding='utf-8') as f:
my_list = []
s = f.read()
my_list = s.split(',')
print(my_list)
import json
my_dict = {'name':'ww',"age":18,"like":["学习","游戏"]}
with open('info4.json','w',encoding='utf-8') as f:
json.dump(my_dict,f,ensure_ascii=False,indent=2)
import random
with open('data.txt','w',encoding='utf-8') as f:
for i in range(10):
num = random.randint(10,20)
f.write(str(num)+" ")
list1 = []
with open('data.txt', 'r', encoding='utf-8') as f:
s = f.read()
list1 = s.split(" ")
list1.sort(reverse=True)
with open('data1.txt', 'w', encoding='utf-8') as f:
for i in range(5):
f.write(list1[i]+" ")
看最下面的报错提示
最外层写异常函数
raise:抛出异常 运行到此 即代码报错了