python刪除某一行


整理了網絡上的一些方法,一般有兩種方法:
第一種:是先把文件讀入內存,在內存中修改后再寫入源文件。

例子:將內容包含“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)

第二種:我們可以使用 open() 方法把需要修改的文件打開為兩個文件,然后逐行讀入內存,找到需要刪除的行時,用后面的行逐一覆蓋。實現方式見以下代碼。
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()


---------------------
版權聲明:本文為CSDN博主「qq_31135027」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_31135027/article/details/78908559


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM