2017-04-23 50 views
1

我正在學python。我想問問是否有方法輸入數據,找到文本文件中的數據並將其刪除?如何刪除文本文件中的輸入?

舉例來說,在我的文本文件

PSP0101 PMF0101 PHP0101

但我想只刪除PMF0101。因此,它會變成這個樣子

PSP0101 PHP0101

謝謝youu

回答

1

我想你可以使用:

import re 
# read the file contents 
the_file = open('some_file.txt', 'r') 
data = the_file.read() 
the_file.close() 

# find, replace, and write to file 
to_remove = "PMF0101" 
data = re.sub(r"{}\s+".format(re.escape(to_remove)), "", data) 
the_file = open('some_file.txt', 'w') 
the_file.write(data) 
the_file.close() 
+0

非常感謝你!!!! –

+0

非常歡迎@ S.Iskandr很高興解決問題。如果我的答案對您有幫助,請考慮投票1 +▲,並通過在投票箭頭中間點擊複選標記✔接受它作爲正確答案,tks! –

+0

你介意如果我問你如何循環這整個事情? –