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')
来源:https://www.cnblogs.com/syqq/p/10321616.html