[英]Remove entire line in text file that contain with specific word/string in python
[英]Python - Remove entire Line in file using specific data
我在這里是因為我用盡了所有資源來構建此程序...
我想使用像這樣的特定數據刪除文件的一行
代碼\\ t名稱\\ t Colum2 \\ t Colum3 \\ t Colum4 \\ t Colum5 \\ n
我想根據代碼刪除整行
如果我鍵入代碼,則* .py將搜索包含該字符串的行並將其刪除。
有什么好心可以幫助我嗎?
假設以下輸入(在generateata.com上生成 )並保存為input.txt:
1 Jennifer O. Ingram P.O. Box 724, 4252 Arcu. St.
2 Lacy N. Fields 5998 Scelerisque Road
3 Blythe P. Abbott Ap #251-2931 Magna. Rd.
4 Alyssa Y. Cobb 438-8110 Enim. Rd.
5 Peter Z. May Ap #271-8340 Eget Avenue
6 MacKenzie A. Santos 8366 Nunc. St.
7 Kevyn C. Willis Ap #583-9635 Erat Avenue
8 Nissim E. Ward 7606 Duis Rd.
9 Duncan J. Armstrong Ap #164-282 Id, St.
10 Jesse B. Barnett P.O. Box 742, 5758 Sagittis Street
以下代碼將刪除代碼為5的行:
# Declare which code you want to delete.
# This can be further improved by being a parameter
# or read from outside the script.
code = 5
removed_lines = 0
f = open("input.txt","r+")
lines = f.readlines()
f.seek(0)
for line in lines:
# Writes to the file all the lines except for those that
# begin with the code declared above.
if not line.startswith(str(code)):
f.write(line)
else:
print("removed line %s" % line)
removed_lines += 1
f.truncate()
f.close()
print("%d lines were removed" % removed_lines)
而input.txt將是:
1 Jennifer O. Ingram P.O. Box 724, 4252 Arcu. St.
2 Lacy N. Fields 5998 Scelerisque Road
3 Blythe P. Abbott Ap #251-2931 Magna. Rd.
4 Alyssa Y. Cobb 438-8110 Enim. Rd.
6 MacKenzie A. Santos 8366 Nunc. St.
7 Kevyn C. Willis Ap #583-9635 Erat Avenue
8 Nissim E. Ward 7606 Duis Rd.
9 Duncan J. Armstrong Ap #164-282 Id, St.
10 Jesse B. Barnett P.O. Box 742, 5758 Sagittis Street
如果文件很大,腳本的運行可能會花費更多時間和資源。
您可以讀取文件,然后在寫入模式下將其打開,然后僅寫入開頭沒有該代碼的行。
//Open in read mode
f = open("yourfile.txt","r")
lines = f.readlines()
f.close()
//if code is 8
code = 8
//Open in write mode
f = open("yourfile.txt","w")
for line in lines:
arr = line.split('\t')
if arr[0]!=code: //Check for the code to avoid
f.write(line)
f.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.