Python 官方文档:入门教程 => 点击学习
整理了网络上的一些方法,一般有两种方法:第一种:是先把文件读入内存,在内存中修改后再写入源文件。 例子:将内容包含“123”的所有行删去: with
第一种:是先把文件读入内存,在内存中修改后再写入源文件。
例子:将内容包含“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()
--结束END--
本文标题: python--文件操作删除某行
本文链接: https://www.lsjlt.com/news/190654.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0