
1.文件读写操作
'''
语法:
fp = open(文件,模式,编码集)
fp => 文件的io对象(文件句柄)
i => input 输入
o => outpur 输出
fp.read() 读取文件内容
fp.write() 写入文件的内容
'''
fp = open("ceshi1.txt",mode="w",encoding="utf-8")
fp.write("把大象怼进去")
fp.close()
fp = open("ceshi1.txt",mode="r",encoding="utf-8")
res = fp.read()
fp.close()
print(res)
2.文件二进制读写
'''
二进制字节流:用于传输数据或者存储数据的一种数据格式
b"abc" b开头的字节流要求数据只能是ascii编码中的字符,不能是中文
# 将字符串和字节流(Bytes流)类型进行转换(参数写成转化的字符编码格式)
# encode() 编码 将字符串转化为字节流(Bytes流)
# decode() 解码 将Bytes流转化为字符串
'''
data = "中文".encode("utf-8")
print(data, type(data))
res = data.decode("utf-8")
print(res,type(res))
data = "中文".encode("utf-8")
print(len(data))
print("我爱你".encode())
res = b'\xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0'.decode()
print(res)
'''如果存储的是二进制字节流,指定模式wb,不要指定encoding编码集,否则报错'''
fp = open("ceshi2.txt",mode="wb")
strvar = "小明".("utf-8")encode
fp.write(strvar)
fp.close
fp = open("ceshi2.txt",mode="rb")
res = fp.read()
fp.close()
print(res)
print(res.decode())
'''所有的图片,音频,视频都需要通过二进制字节流来进行存储传输'''
fp = open(r"D:\tmp\code\day06\集合.png",mode="rb")
res = fp.read()
fp.close()
print(len(res))
fp = open("集合2.png",mode = "wb")
fp.write(res)
fp.close()
3.文件操作的扩展模式
"""
# (utf-8编码格式下 默认一个中文三个字节)
# read() 功能:读取字符的个数(里面的参数代表字符个数)
注意:从当前光标往右边读
# seek() 功能:调整指针的位置(里面的参数代表字节个数)
seek(0) 把光标移动到0字节的位置上
seek(0,2) 把光标移动到文件的末尾
# tell() 功能:当前光标左侧所有的字节数(返回字节数)
"""
fp = open("ceshi4.txt",mode= "r+",encode="utf-8")
res = fp.read()
fp.write("ab")
fp.seek(0)
print(fp.read())
fp.close()
fp = open("ceshi3.txt",mode="r+",encoding="utf-8")
fp.seek(0,2)
fp.write("cd")
fp.seek(0)
res = fp.read()
print(res)
fp.close()
fp = open("ceshi4.txt",mode="w+",encoding+"utf-8")
fp.write("abc)
fp.seek(0)
print(fp.read())
fp.close()
#(4)a+ 可读可写,追加写入(默认可以创建新的文件)
fp = open("ceshi5.txt",mode="a+",encoding="utf-8")
fp.write("def")
# 读内容
fp.seek(0)
print(fp.read())
fp.close
#(5).seek,tell,read之间的使用
'''
r+模式基于当前光标所在的位置进行写入覆盖
a+模式会强制把光标放到文件末尾进行追加写入
'''
fp = open("ceshi5.txt",mode=a+"",encoding="utf-8")
fp = open("ceshi5.txt",mode="a+",encoding="utf-8")
fp.seek(3) # 从头数3个字节的位置
# fp.write("zxc") #模式会强制把光标放到文件末尾进行追加写入
print(fp.read())
fp.close()
#(6)seek,tell,read之间的使用
fp = open("ceshi5.txt",mode="r+".encoding="utf-8")
fp.seek(4)
# tell 当前光标左边所有内容的字节数
res = fp.tell()
print(res)
# 在r+模式下read(2)代表读取2个字符 在rb模式下read(2)代表读取2个字节
fp.read(2) # 当前光标往右所有的字符内容
print(fp.tell())
fp.close()
#(7)注意点(seek在移动时,又可能移动到某个汉字的字节中间,导致原字节无法解析)
fp = open("ceshi6.txt",mode="r+",encoding="utf-8")
fp.seek(3)
print(fp.read())
fp.close()
print("你".encode())
#(8)with 自动实现关闭文件操作
# 方法一:读取二进制字节流
with open=("集合2.png",mode="rb") as fp:
res = fp.read()
with open=("集合2.png",mode="wb") as fp:
res = fp.write(res)
# 方法二:继续简写
with open=("集合2.png",mode="rb") as fp1,with open=("集合2.png",mode="wb") as fp2:
res = fp1.read()
fp2.write(res)
"""
"""
open("ceshi1.txt",mode="w",encoding="utf-8")
fp.write("abc")
# 手动刷新缓冲区,直接把内容写入到文件
while True:
pass
fp.close()
4.文件相关函数
"""fp这个对象本身是迭代器,可以把文件中的内容按照换行一行一行遍历出来"""
fp = open("ceshi1.txt",mode="r",encoding="utf-8")
print(fp.readable())
print(fp.writable())
for i in fp:
print(i)
with open("ceshi1.txt",mode="r",encoding="utf-8") as fp:
res = fp.readline()
while res:
print(res)
res = fp.readline()
with open("ceshi1.txt","mode"="r",encoding="utf-8") as fp:
"""
读取的字符数量>实际当前字符数量的时候 => 按照当前行读取
读取的字符数量 <实际当前字符数量的时候=> 按照实际数量来读
"""
res = fp.readline(300)
print(res)
lst_new = []
with open("ceshi1.txt",mode="r+",encoding="utf-8") as fp:
list = fp.readlines()
for i in lst:
lst.new.append(i.strip())
print(lst_new)
lst = ["床前明月光","疑是地上霜","举头望明月","低头思故乡"]
with open("ceshi2.txt",mode="w+",encoding="utf-8"):
fp.writelines(lst)
lst_new = []
lst.insert(-1"alex你真帅呀")
for i in lst:
lst_new.append(i + "\n")
print(lst_new)
with open("ceshi2.txt",mode="w+",encoding="utf-8") as fp:
fp.writelines(lst_new)
lst = [1,2,3]
with open("ceshi2.txt",mode="w+",encoding="utf-8") as fp:
fp.writelines(lst)
with open("ceshi2.txt",mode="r+",encoding+"utf-8") as fp:
fp.truncate(3)
"""
seek(字节)
truncate(字节)
read(字符/字节)
readline(字符/字节)
"""
5.文件操作作业
"""
一.有如下文件,1.txt,里面的内容为:
键盘敲烂,
月薪过万,
键盘落灰
狗屎一堆
"""
"""
分别完成以下功能:
a:将原文件全部读出来并打印
b:在原文件后面追加一行内容:信不信由你,反正我信了.
c:将原文件全部读出来,并在后面添加一行内容:信不信由你,反正我信了
d:将原文件全部清空,换成下面的内容:
每天坚持一点,
每天努力一点,
慢慢你会发现,
你的进步越来越大.
e:将原文件内容全部读取出来
并在'键盘落灰'这一行的前面加一行,'年薪百万'
然后将更改之后的新内容,写入到一个新文件:a1.txt
"""
with open('1.txt',mode='r',encoding='utf-8') as fp:
res = fp.read()
print(res)
with open('1.txt',mode='a',encoding='utf-8') as fp:
fp.write("\n\t信不信由你,反正我信了.")
with open('1.txt',mode='a+',encoding='utf-8') as fp:
print(fp.read())
fp.write("\n\t信不信由你,反正我信了.")
with open('1.txt',mode='w',encoding='utf-8') as fp:
res = """\t每天坚持一点,
每天努力一点,
慢慢你会发现,
你的进步越来越大.
"""
fp.write(res)
with open('1.txt',mode='r+',encoding='utf-8') as fp:
lst = fp.readlines()
print(lst)
lst.insert(-2,"\t年薪百万,\n")
with open('a1.txt',mode='w+',encoding='utf-8') as fp1:
fp1.writelines(lst)
"""
二.有如下文件,1.txt,里面的内容为:
葫芦娃,葫芦娃,
一根藤上七个瓜,
风吹雨打都不拍,
啦啦啦啦.
分别完成下面的功能:
a:以r+的模式打开原文件,判断原文件是否可读,是否可写
b:以r的模式打开原文件,利用for循环遍历文件对象
c:以r的模式打开原文件,以readlines()方法读取出来,并循序遍历
d:以r模式读取"葫芦娃,葫芦娃,"前四个字符
e:以r模式读取第一行内容,并去除此行前后的空格,制表符,换行符
f:以r模式打开文件,从"风吹雨打...."开始读取,一直读到最后
g:以a+模式打开文件,先追加一行:"喜洋洋与灰太狼"然后再全部读取出来
h:截取原文件,截取内容:"葫芦娃,葫芦娃"
"""
with open('a1.txt', mode="r+", encoding="utf-8") as fp1:
print(fp1.readable(), fp1.writable())
with open('a1.txt', mode="r", encoding="utf-8") as fp2:
for line in fp2:
print(line.strip())
with open('a1.txt', mode="r", encoding="utf-8") as fp3:
res = fp3.readlines()
for i in res:
print(i.strip())
with open('a1.txt', mode="r", encoding="utf-8") as fp4:
print(fp4.read(4))
with open('a1.txt', mode="r", encoding="utf-8") as fp5:
print(fp5.readline().strip())
with open('a1.txt', mode="r", encoding="utf-8") as fp6:
lst = fp6.readlines()
for i in lst[-2:]:
print(i)
with open('a1.txt', mode="a+", encoding="utf-8") as fp6:
fp6.write("喜洋洋与灰太狼.")
fp6.seek(0)
print(fp6.read())
with open('a1.txt', mode="r+", encoding="utf-8") as fp7:
fp7.truncate(24)
""""
三.文件内容a.txt内容:每一行内容分别为商品名字,价钱,个数
apple 10 3
tesla 10000 1
mac 3000 2
lenovo 30000 3
chicken 10 3
变成如下数据格式,并计算出总价格
[
{'name':'apple','price':10,'amount':3}
{'name':'tesla','price':10,'amount':1}
]
"""
with open('a1.txt', mode='r', encoding='utf-8') as fp8:
lst = []
total = 0
for i in fp8:
res = (i.strip().split())
dic = {}
dic['name'] = res[0]
dic['price'] = int(res[1])
dic['amount'] = int(res[2])
sum = dic['price'] * dic['amount']
total += sum
lst.append(dic)
print("1.数据格式:", lst)
print("2.总价格:", total)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步