我來這裏是因爲我耗盡了我所有的資源來建造這個節目......的Python - 刪除文件全線使用特定的數據
我想刪除使用特定的數據這樣
一個文件的行編號\ t姓名\ t Colum2 \ t Colum3 \ t Colum4 \ t Colum5 \ n
我想刪除基於代碼
整行,如果我鍵入鱈魚e,* .py將搜索包含此字符串的行,並將其刪除。
任何好的靈魂能幫助我嗎?
我來這裏是因爲我耗盡了我所有的資源來建造這個節目......的Python - 刪除文件全線使用特定的數據
我想刪除使用特定的數據這樣
一個文件的行編號\ t姓名\ t Colum2 \ t Colum3 \ t Colum4 \ t Colum5 \ n
我想刪除基於代碼
整行,如果我鍵入鱈魚e,* .py將搜索包含此字符串的行,並將其刪除。
任何好的靈魂能幫助我嗎?
假設下面的輸入(上generatedata.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
如果文件很大,腳本的運行可能需要更多的時間我和資源。
你解決了我工作中的4個問題。 –
你想查看是否有實際的行被刪除? – AllBlackt
您可以讀取文件,然後在寫入模式下打開它,並且只寫入在開始時沒有該代碼的行。
//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()
你能給我們一個示例輸入和預期輸出嗎?你到目前爲止寫的是什麼?你的問題有點含糊。 –