文件处理:
文件的打开模式:b模式
强调:
1、与t模类似不能单独使用,必须是rb,wb,ab
2、b模式下读写都是以bytes单位的
3.b模式下一定不能指定encoding参数


rb模式:只读,将内容以二进制读出来
with open('1.jpg',mode='rb')as f:
data=f.read()
print(data) #读取图片

with open('a.txt',mode='rb') as f:
data=f.read()
print(data.decoe('utf-8')) #读取文档


wb模式:只写
with open('a.txt,mode='wb') as f:
msg='你好啊'


ab模式:追加写,将内容以二进制写进去,需要转换encode

with open('a.txt',mode='ab') as f:
f.write('你好’,encode('utf-8'))


总结:在不考虑文件格式的情况下用b模式更好。

 

文件的拷贝:
以读的方式打开文件,在你想拷贝到的文件夹下建一个跟原文件名一样的新文件,这个文件现在是空的,
然后读原文件的内容,写在新文件中,读一行写一行。

import sys

l=sys.srgv

src_file_path=l[1]
dst_file_path=l[2]

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)


文件的修改:

修改文件方式一:
seek 光标移动,偏移单位是字节,
先将硬盘的数据读入内存,在内存中修改后,再把修改的结果覆盖写入原文件
缺点:文件过大,会占用过多内存,机器会卡

with open('x.txt',mode='r',encoding='utf-8') as f:
data=f.read()
data=.repace('需要修改的内容’,'修改后的内容')
with open('x.txt',mode='w',encoding='utf-8') as f:
f.write(data)


修改文件方式二:
以读的方式打开原文件,以写的方式打开一个新文件

import os

with open(user.txt',mode='rt',encoding='utf-8')as read_f,\
open('user.txt.swap',mode='wt',encoding='utf-8') as write_f:
for line in read_f:
if 'gao' in line:
line=line.replace('gao','gao[帅]')
write_f.write(line)

os.remove('user.txt')
os.rename('user.txt.swap','user.txt')

 

posted on 2018-03-23 21:07  muzinianhua  阅读(64)  评论(0编辑  收藏  举报