3.23

文件的打开方式b

b模式类型跟t模式类型一样  不能单独使用,必须是rb wb ab

b模式下读写都是以bytes为单位的

b模式下一定不能指定encoding参数

open(‘文件的路径’‘打开文件的模式‘)

rb模式:

with open('a.txt',mode='rb',)as z:
res=z.read()
print(res.decode('utf-8'))
print(res)

with open('2.jpg', mode='rb', )as z:
     data=z.read()
     print(data)

wb模式:
with open('a.txt',mode='wb',)as z:
msg='cnm'
z.write(msg.encode('utf-8'))

ab模式:
with open('a.txt', mode='ab', )as z:
     res='刀妹’
 z.write(res.encode('utf-8'))


 
import sys

l=sys.argv # 把命令行中解释器后空格分割的所有参数都存成列表
print(l)

src_file_path=l[1]
dst_file_path=l[2]
print(src_file_path)
print(dst_file_path)

with open(r'%s' %src_file_path,mode='rb') as src_f,
open(r'%s' %dst_file_path,mode='wb') as dst_f:

for line in src_f:
dst_f.write(line)
文件的修改
f.seek( )偏移单位是字节
修改文件的方式:
1.先把文件内容全部读入内存
2.然后在内存中完成维修
3.再把改成的结果覆盖写入文件
with open('a.txt', mode='r',encoding='utf-8' )as z:
data = z.read()
data = data.replace('锐雯', '吴佩其[老男孩第二帅的人]')

with open('a.txt', mode='w', encoding='utf-8') as z :
z.write(data)
缺点 修改文件是会因为文件内容过大,占用内存过多 会卡机

以读的方式打开原文件,写的方式打开一个新文件
import os
with open('a.txt1', mode='r',encoding='utf-8' )as z,
open('b.txt', mode='w', encoding='utf-8')as f:
for line in z:
if '锐雯' in line :
line = line.replace('锐雯', '吴佩其[老男孩第二帅的人]')
f.write(line)

os.remove('a.txt1')
os.rename('b.txt','a.txt1')


原文地址:https://www.cnblogs.com/yftzw/p/8631014.html