lg04551

导航

 

1.bytes 类型转成utf-8可以存硬盘,可以基于网络传输

,\转移

 

2、b模式

文件的打开模式b模式
强调:
1、与t模式类似不能单独使用,必须是rb,wb,ab

rb模式

with open('l.txt',mode='r',) as f:

data=f.read()

print(data.decode('utf-8'))

print(type(data))

wb模式

with open ('b.txt',code='wb') as f:

msg='你好'

f.write(msg.encode('gbk'))

with oper('1.jpg',mode='rb') as f:

  data=f.read()

  print(type(data))

  print(data.decode('utf-8'))

2、b模式下读写都是以bytes单位的
3、b模式下一定不能指定encoding参数

seek(n)n=1,2,3,偏移量的单位是字节

with open('user.txt','r+',encoding='utf-8')

  f.seek(5)

print(f.tell())

print(f.reak())

ab 模式

with open('b.txt',mode='ab') as f:

  f.write('你好'.encode('utf-8'))

修改文件方式 一:

1、先把文件内容全部读入内存

2、然后在内存中完成修改

3、再把修改后的文件覆盖写入原文件

缺点:点内存

with open('user.txt',mode='r',encoding='utf-8') as f:

  data=f.read()

  data=data.replace('aa','bb' )

with open('user.txt',mode='w',encoding='utf-8') as f

  f.write(data)

 

修改文件方式二:

1、以读找开原文件,以的方式打开一个新文件并把原文件删除,占空间

import os

with open('user.txt',mode='r',encoding='utf-8') as old_f,\

open('user1.txt',mode='r',encoding='utf-8') as new_f

for i in old_f

  if 'aa' in i:

  i=i.replace('aa','bb')

new_f.write(i)

os.remove('user.txt')

os.remove('user1.txt','user')

 

两种方式各有利敝

 

posted on 2018-03-23 14:31  lg04551  阅读(107)  评论(0编辑  收藏  举报