python的文件处理补充和文件修改

。文件读写
r+t:可读、可写

w+t:可写、可读
with open('b.txt','w+t',encoding='utf-8') as f:
    print(f.readable())
    print(f.writable())
a+t:可追加写、可读

r+b
w+b
a+b

with open('b.txt',mode='rb') as f:
    data=f.read()
    print(data.decode('utf-8'))

with open('b.txt',mode='rt',encoding='utf-8') as f:
    data=f.read()
    print(data)

with open('a.txt',mode='r+',encoding='utf-8') as f:
    print(f.readline())
    print(f.readline())
    f.write('小红帽')#总是会加在文件最后
二,控制文件指针的移动
f.seek(offset,whence)
offset代表文件的指针的偏移量,单位是字节bytes
whence代表参考物,有三个取值
0:参照文件的开沟
1:参照当前文件指针所在位置
2: 参照文件末尾
ps:快速移动到文件末尾f.seek(0,2)

强调:其中whence=1和whence=2只能在b模式下使用
f=open('c.txt',mode='rt',encoding='utf-8')
# f.seek(9,0)
print(f.tell()) # 每次统计都是从文件开头到当前指针所在位置
# print(f.readline())

f.close()


f=open('c.txt',mode='rb')
f.readline()
f.seek(6,1)
print(f.readline().decode('utf-8'))
print(f.tell())
f.close()


f=open('c.txt',mode='rb')
f.seek(-9,2)
print(f.readline().decode('utf-8'))
print(f.tell())
f.close()
了解(**)
只有在t模式下的read(n),n代表的是字符个数,除此之外其他但凡涉及文件指针的移动
都是以字节为单位的
f=open('c.txt',mode='rt',encoding='utf-')
print(f.read(3))
f.close()

f=open('c.txt',mode='rb',)
print(f.read(3).decode('utf-8'))
f.close()


ab a+b r+b
f=open('b.txt',mode='at',)
f.truncate(9) # 参照物永远是文件开头
f.close()
三,文件的修改
 
 
with open('c.txt','r+t',encoding='utf-8') as f:
    f.seek(21,0)
    f.write('[我擦勒]')会覆盖原来的数据

修改文件内容的方式一:
思路:先将原文件内容一次性全部读入内存,然后在内存修改完毕后,再
覆盖写回原文件
优点:在修改期间,文件内容只有一份
缺点:当文件过大的情况下或占用过多的内存空间

with open('d.txt','rt',encoding='utf-8') as read_f:
    msg=read_f.read()
    msg=msg.replace('alex','xiang')
    # print(msg)

with open('d.txt','wt',encoding='utf-8') as write_f:
    write_f.write(msg)

修改文件内容的方式二:
思路:
1、以读的方式打开原文件,以写的方式打开一个新文件
2、从原文件中循环读取每一行内容修改后写入新文件
3、删除原文件,将新文件重命名为原文件的名字

优点:同一时刻只有一行内容存在于内存中
缺点:在修改期间,文件内容始终存在两份,但修改完毕后会只留一份
import os
with open('d.txt','rt',encoding='utf-8') as read_f,\
        open('sd.txt.','wt',encoding='utf-8') as write_f:
    for line in read_f:
        write_f.write(line.replace('xiang','ALEXSB'))

os.remove('d.txt') # 删除老文件
os.rename('sd.txt','d.txt')


猜你喜欢

转载自blog.csdn.net/qq_35540539/article/details/80594538