Python文件相关函数-----23

文件

  • 长久保存信息的一种数据信息集合
  • 常用操作
    • 打开关闭(文件一旦打开,需要关闭操作)
    • 读写内容
    • 查找

      open函数

  • open函数负责打开文件,带有很多参数
  • 第一个参数:必须有,文件的路径和名称
  • mode:表明文件用什么方式打开
    • r:以只读方式打开
    • W: 写方式打开,会覆盖以前内容
    • x:创建方式打开,如果文件已经存在则报错
    • a: append方式,已追加的方式对文件内容进行写入
    • b: binary方式,二进制方式写入
    • t: 文本方式打开
    • +:可读写

In [2]:

 

# 打开文件,用写的方式
#r表示后面字符串内容不需要转移义
#f称之为文件句柄
f = open(r'hello.txt','w')
#文件打开后必须关闭
f.close()
#以写的方式打开文件,默认如果没有文件则创建

with 语句

  • with语句使用的技术是一种成为上下文管理协议的技术(ContextManagementProtocal)
  • 自动判断文件的作用域,自动关闭不使用的打开的文件句柄

In [4]:

 

#with 语句案例
with open (r'hello.txt','r') as f :
    pass
# 下面语句快开始对文件f进行操作
#本模块中不需要使用close关闭文件f

In [12]:

 

#with 语句案例
with open (r'hello.txt','r') as f :
    strline = f.readline() #一行一行读
#此语句保证能够完整读取文件直到结束
    while strline:
        print(strline)
        strline = f.readline()
hello

你好啊

good

哈哈哈哈

In [14]:

 

#list能用打开的文件作为参数,把文件中每一行内容作为一个元素
with open (r'hello.txt','r') as f :
    #以打开的文件f作为参数,创建列表
    l = list(f)
    for line in l :
        print(line)
hello

你好啊

good

哈哈哈哈

In [17]:

 

#read 按字符读取文件
#允许输入参数决定读取几个字符,如果没有指定,就从当前位置读取到结尾
with open (r'hello.txt','r') as f :
    strChar = f.read()
    print(len(strChar))
    print(strChar)
19
hello
你好啊
good
哈哈哈哈

seek(offset,from)

  • 移动文件的读取位置,也叫读取指针
  • from的读取范围:
    • 0:从文件头开始偏移
    • 1:从文件当前位置开始偏移
    • 2:从文件末尾开始偏移
  • 移动的单位是字节(byte)
  • 一个汉字有若干个字节构成
  • 返回文件只针对当前位置

In [21]:

 

#seek案例
# 打开文件后从第6字节开始读取
# 打开读写指针在0 处,即文件的开头
with open (r'hello.txt','r') as f :
    #seek移动单位是字节
    f.seek(5,0)
    strChar = f.read()
    print(strChar)
你好啊
good
哈哈哈哈

In [25]:

 

 
#关于读取文件的练习
#打开文件,5个字符一组读出内容,然后显示在屏幕上
#每读一次,休息一秒
import time
with open (r'hello.txt','r') as f :
    strChar = f.read(5)
    while strChar:
        print(strChar)
        time.sleep(1)
        strChar = f.read(3)
hello

你好
啊
g
ood

哈哈
哈哈

In [27]:

 

#tell函数:用于显示文件读写指针当前位置
with open (r'hello.txt','r') as f :
    strChar = f.read(4)
    pos = f.tell()
    while strChar:
        print(pos)
        print(strChar)
        strChar = f.read(4)
        pos = f.tell()
 
        #结果证明:
        #tell的返回数字的单位是byte
        #read是以字节为单位
4
hell
12
o
你好
18
啊
go
24
od
哈
33
哈哈哈

文件的写操作-write

  • write(str):把字符串写入文件
  • writeline(str):把字符按行写入文件
  • 区别:
    • write函数的参数只能是字符串
    • writeline参数可以使字符串,也可以是字符序列

In [ ]:

 

 
# write案例
# 向文件追加一句诗
# a 代表追加方式打开
with open (r'hello.txt','r') as f :
    f.write('student')

In [ ]:

 

#直接写入行,用writelines
# writelines表示写入很多行,参数可以使list格式
# a 代表追加方式打开
with open (r'hello.txt','r') as f :
    f.writelines('student')
    f.writelines('teacher')    

In [30]:

 

 
l = ['hello','hahaha']
with open (r'hello.txt','w') as f :
    f.writelines(l)   

持久化 - pickle

  • 序列化(持久化,落地):把程序运行中的信息保存在磁盘上
  • 反序列化:序列号的逆过程
  • pickle:Python提供的序列化模块
  • pickle.dump:序列化
  • pickle.load:反序列化

In [32]:

 

 
#序列化案例
import pickle
age = 19
with open (r'hello.txt','wb') as f :
    pickle.dump(age,f)

In [33]:

 

 
#反序列化案例
with open (r'hello.txt','rb') as f :
    age = pickle.load(f)
    print(age)
19

In [35]:

 

#序列化案例
import pickle
a = [13,'dana','hahaha',[12,45]]
with open (r'hello.txt','wb') as f :
    pickle.dump(a,f)

In [36]:

 

#反序列化案例
with open (r'hello.txt','rb') as f :
    a = pickle.load(f)
    print(a)
[13, 'dana', 'hahaha', [12, 45]]

持久化-shelve

  • 持久化工具
  • 类似字典,用kv对保存数据,,存取方式跟字典也类似
  • open,close
  • 特性:
    • 不支持多个应用并行写入
      • 为了解决这个问题,open的时候可以使用flag=r
    • 写回问题
      • shelve情况下不会等待持久化对象进行任何修改
      • 解决方法:强制写回 writeback = True

In [38]:

 

 
#使用shelve创建文件并使用
import shelve
#打开文件
#shv相当于一个字典
shv = shelve.open(r'shv.db')
shv['one'] = 1
shv['two'] = 2
shv.close()
#shelve自动创建的不仅仅是一个shv.db文件,还包括其他格式文件

In [43]:

 

 
#shelve读取案例
try:
    shv = shelve.open(r'shv.db')
    print(shv['one'])
    print(shv['two'])
finally:    
    shv.close()
1
2

In [45]:

 

 
#shelve之只读打开
shv = shelve.open(r'shv.db',flag = 'r')
try:
    k1 = shv['one']
    print(k1)
finally:    
    shv.close()
1

In [50]:

 

 
#写
shv = shelve.open(r'shv.db')
try:
    shv['one'] = {'ss':1}
finally:    
    shv.close()
shv = shelve.open(r'shv.db')
try:
    one = shv['one']
    print(one)
finally:
    shv.close()
{'ss': 1}

In [52]:

 

#shelve 忘记写回,需要使用强制写回
shv = shelve.open(r'shv.db')
try:
    k1 = shv['one']
    print(k1)
    #此时,一旦shelve关闭,则内容还是在内存中,为写回数据库
    k1['haha']=100
finally:    
    shv.close()
shv = shelve.open(r'shv.db')
try:
    k1 = shv['one']
    print(one)
finally:
    shv.close()
{'ss': 1}
{'ss': 1}

In [56]:

 

 
#shelve 忘记写回,需要使用强制写回  - 添加写回后
shv = shelve.open(r'shv.db', writeback = True)#强制写回
try:
    k1 = shv['one']
    print(k1)
    #此时,一旦shelve关闭,则内容还是在内存中,为写回数据库
    k1['haha']=100
finally:    
    shv.close()
shv = shelve.open(r'shv.db')
try:
    k1 = shv['one']
    print(one)
finally:
    shv.close()
{'ss': 1, 'haha': 100}
{'ss': 1}

In [57]:

 

#shelve使用with管理上下文
with shelve.open(r'shv.db', writeback = True) as shv:
    k1 = shv['one']
    print(k1)
    k1['one']= 10000
 
with shelve.open(r'shv.db') as shv:
    print(shv['one'])
{'ss': 1, 'haha': 100}
{'ss': 1, 'haha': 100, 'one': 10000}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

What’smean

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值