文件的其他操作

六眼飞鱼酱① 提交于 2019-12-19 23:16:18

truncate只能用在追加模式下

f=open('D:\oldboy.txt',encoding='utf-8',mode='a')

content=f.truncate(7)  #安字节截取

print(content)

f.close()

操作方法:

read()

read(n)

readline()

readlines()

tell()

seek()

truncate()

writeable()

readable()

with open用法

功能一:省去关闭文件句柄

with open('a.txt','w') as f:

      pass

使用with open,不用去写f.close()

功能二:可以打开多个文件句柄

with open('log',encoding='utf-8') as f1, \

       open('log1',encoding='utf-8',mode='w')  as f2

print(f1.read())

print(f2.read())

  四)a+追加读

f=open('log',encoding='utf-8',mode='a+')

f.write('aaa')

content=f.read()

print(content)

f.close()

文件的修改原理

1.将原文件读取到内存

2.在内存中进行修改,形成新的内容

3.将新的字符串重新写入新文件

4.将原文件删除

5.将新文件重命名成原文件

import os

with open('log',encoding='utf-8' ) as f1,\

        open('log.bak',encoding='utf-8',mode='w') as f2

        for i in f1:

             new_content=i.replace('sb','alex')

             f2.write(new_content)

os.remove('log')

os.rename('log.bak','log')

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!