发布时间:2019-09-18 07:23:02编辑:auto阅读(1608)
第一种:是先把文件读入内存,在内存中修改后再写入源文件。
例子:将内容包含“123”的所有行删去:
with open('C:/Users/lai/Desktop/1.txt','r') as r:
lines=r.readlines()
with open('C:/Users/lai/Desktop/1.txt','w') as w:
for l in lines:
if '123' not in l:
w.write(l)
with open('file.txt', 'r') as old_file:
with open('file.txt', 'r+') as new_file:
current_line = 0
# 定位到需要删除的行
while current_line < (del_line - 1):
old_file.readline()
current_line += 1
# 当前光标在被删除行的行首,记录该位置
seek_point = old_file.tell()
# 设置光标位置
new_file.seek(seek_point, 0)
# 读需要删除的行,光标移到下一行行首
old_file.readline()
# 被删除行的下一行读给 next_line
next_line = old_file.readline()
# 连续覆盖剩余行,后面所有行上移一行
while next_line:
new_file.write(next_line)
next_line = old_file.readline()
# 写完最后一行后截断文件,因为删除操作,文件整体少了一行,原文件最后一行需要去掉
new_file.truncate()
上一篇: Powershell进阶学习(3) Po
下一篇: Python3 完整实现DNN
47840
46386
37279
34731
29312
25970
24909
19949
19541
18026
5790°
6411°
5926°
5960°
7063°
5911°
5942°
6437°
6404°
7776°