文件
open函数
r:以只读方式打开
w:写方式打开,会覆盖以前的内容,没有文件的话,会自动创建
x:创建方式打开,如文件已经存在,报错
a:append方式,以追加的方式对文件内容进行写入
b: binary方式,二进制方式写入
t: 文本方式打开
+: 可读写
f.open(r"test01.txt",'w')
f.close()
with语句
with语句使用的技术是一种成为上下文管理协议的技术(ContextManagementProtocal)
自动判断文件的 作用域, 自动关闭不在使用的打开的文件句柄
with open(r'xiaoxiongceshi01.txt','r')as f:
#按行读取内容
strline=f.readline()
#完整读取文件知道结束
while strline:
print(strline)
strline=f.readline()
# list能用打开的文件作为参数,把文件内每一行内容作为一个元素
with open(r'xiaoxiongceshi01.txt','r')as f:
#以打开的文件f作为参数,创建列表
l=list(f)
for line in l:
print(line)
# read是按字符读取文件内容
# 允许输入参数决定读取几个字符,如果没有制定,从当前位置读取到结尾
# 否则,从当前位置读取指定个数字符
#f.read(1)就是读取当前一个字符
with open(r'xiaoxiongceshi01.txt','r')as f:
print(f.read())
#使用read读取文件,每次读取一个,使用循环读完
with open(r'xiaoxiongceshi01.txt','r')as f:
strChar=f.read(1)
while strChar:
print(strChar)
strChar=f.read(1)
seek(offset,from)
移动文件的读取位置,也叫读取指针
from的取值范围:
0: 从文件头开始偏移
1:从文件当前位置开始偏移
2: 从文件末尾开始偏移
移动的单位是字节(byte)
一个汉子由若干个字节构成
返回文件只针对 当前位置
#注意移动的是字节,一个汉字一般有2个字节,所以要注意不要刚好把一个汉字劈开,这样就会报错,乱码
with open(r'xiaoxiongceshi01.txt','r')as f:
f.seek(9,0)#第8个字节开始读取
strChar = f.read()
print(strChar)
#打开文件,三个字符一组读出内容,然后显示在屏幕上,每读一次,休息一秒钟
import time
with open(r'xiaoxiongceshi01.txt','r')as f:
strChar=f.read(3)
while strChar:
print(strChar)
time.sleep(1)
strChar=f.read(3)
# tell函数: 用来显示文件读写指针的当前位置
with open(r'xiaoxiongceshi01.txt','r')as f:
strChar = f.read(3)
print(f.tell())=>4
# tell的返回数字的单位是byte
# read是以字符为单位
文件的写操作-write
write(str): 把字符串写入文件
writeline(str): 把字符串按行写入文件
区别:
write函数参数只能是字符串
writerline参数可以是字符串,也可以是字符序列
# writelines表示写入很多行,参数可以是list格式
l=["i","love","you"]
with open(r'xiaoxiongceshi01.txt','a')as f:
f.write("死了毒药爱,\n我爱你\n")
f.writelines("生活不仅有眼前的苟且\n")
f.writelines("还要远方的枸杞\n")
f.writelines(l)
持久化 - pickle
序列化(持久化,落地):把程序运行中的信息保存在磁盘上
反序列化: 序列号的逆过程
pickle: python提供的序列化模块
pickle.dump:序列化
pickle.load:反序列化
# 序列化案例
import pickle
age = [15145,'sad',''sdadasd'']
with open(r'test01.txt', 'wb') as f:
pickle.dump(age, f)
# 反序列化案例
import pickle
with open(r'test01.txt', 'rb') as f:
age = pickle.load(f)
print(age)=>[15145,'sad',''sdadasd'']
持久化-shelve
持久化工具
类似字典,用kv对保存数据,存取方式跟字典也类似
open, close
# 打开文件
import shelve
shv=shelve.open(r'shv.db')
shv['one']=1
shv['two']=2
shv['three']=3
shv.close()
# shelve读取案例
import shelve
shv = shelve.open(r'shv.db')
try:
print(shv['one'])
print(shv['threee'])
except Exception as e:
print("烦死了")
finally:
shv.close()
# shelve 使用with管理上下文环境,不用写try和close了
# shelve忘记写回,需要使用强制写回
import shelve
with shelve.open(r'shv.db', writeback=True) as shv:
shv['one'] = {"eins":1, "zwei":2, "drei":3}
k1 = shv['one']
print(k1)=>{'eins': 1, 'zwei': 2, 'drei': 3}
# 此时,一旦shelve关闭,则内容还是存在于内存中,没有写回数据库
k1["eins"] =1000
with shelve.open(r'shv.db') as shv:
print(shv['one'])=>{'eins': 1000, 'zwei': 2, 'drei': 3}