向文件里写入信息
with open('d:\\grade.txt','w+') as f:
f.write("I am very good")
try:
with open('d:\\grade.txt','w+') as f:
f.write(" I am very happy")
l=["123",'thanks','write']#向文件里写的列表的元素必须是字符串
f.writelines(l)
newL=[line+'\n' for line in l]
f.writelines(newL)
except:
print("文件创建失败")
读取文件信息
try:
with open('d:\\grade.txt','r') as f:
s1=f.read(20)#从当前位置读取20个字节
print(s1)
print(f.tell())#返回文件指针当前所在的位置
f.seek(6,0)#将指针重置在从文件头偏离6个字节的位置,第二个参数表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起
s2=f.read(14)
print(s2)
except FileNotFoundError:
print("文件未被发现")
一行一行读取文件
except:
print("文件创建失败")
try:
with open('d:\\grade.txt','r') as f:
i=1
for line in f:
print("第"+str(i)+"行为 "+line)
i=i+1
except FileNotFoundError:
print("文件读取失败")
二进制文件的写与读
import struct
def m():
with open('d:\\qwert.bin','wb') as f:
s1='123'.encode('utf-8')
s2='789'.encode('utf-8')
a=struct.pack("!10s12si",s1,s2,128)#非字符不需要编码
f.write(a)
with open('d:\\qwert.bin','rb') as f:
a,b,c=struct.unpack("!10s12si",f.read())
print(a.decode('utf-8','ignore'),b.decode('utf-8','ignore'),c)#ignore含中文的时候要加
m()
# 123 789 128
import struct
def m():
with open('d:\\qwert.bin','rb') as f:
a=struct.unpack("!10s12si",f.read())
print(a[0].decode(),a[1].decode())
m()
关于将字节串解读为打包的二进制数据
https://docs.python.org/zh-cn/3.7/library/struct.html
使用pickle实现数据序列化
序列化:将任意的python对象转化为一系列的字节储存到文件中。反序列化恰好相反
序列化对象:
基本类型:布尔型、整型、浮点型、复数型等
对象:字符串、列表、元组、字典和集合等
其他:函数、类、类的实例
序列化方法:
dump():将对象转化为字节流存入文件
load():解析文件中的字节流(反序列化)
str.rstrip([chars])
返回原字符串的副本,移除其中的末尾字符。 chars 参数为指定要移除字符的字符串。 如果省略或为 None,则 chars 参数默认移除空格符。 实际上 chars 参数并非指定单个后缀;而是会移除参数值的所有组合
练习:
def ReadMP(filename):
with open(filename,'r') as f:
a={}
l=f.readline()
while l!='':
if(l[1:3].isdigit() and l[4:6].isdigit() and l[7:9].isdigit() and l[3]==':' and l[6=='.']):
t1=(int(l[1:3]))*60+(int(l[4:6]))*1000+(int(l[7:9])*10000)
a[t1]=l[10:].rstrip()#删掉的是空格
l=f.readline()
return a
def d():
s=input("请输入文件名:")
a=ReadMP(s)
for key in sorted(a):
print(key,a[key])
d()