with open('C:\Users\craig\Downloads\folder\test.txt', 'r') as myfile:
test = myfile.read().replace('', '')
test.txt的是:文件分離 -
hugh:ted
mark:mike
ethan:jay
我將如何讓Python刪除:和過去的一切? 例如,如何刪除:ted,:mike,:jay,而不必手動將其寫入替換部分中?
with open('C:\Users\craig\Downloads\folder\test.txt', 'r') as myfile:
test = myfile.read().replace('', '')
test.txt的是:文件分離 -
hugh:ted
mark:mike
ethan:jay
我將如何讓Python刪除:和過去的一切? 例如,如何刪除:ted,:mike,:jay,而不必手動將其寫入替換部分中?
import fileinput
for line in fileinput.input('C:\Users\craig\Downloads\folder\test.txt', inplace=True):
if ':' in line:
print line.replace(line[line.index(':'):], '')
你可以試試下面的代碼片段。
import re
import fileinput
for line in fileinput.FileInput("/home/dma3node/test.txt", inplace=1):
line = re.sub(r"\:(.*)", "", line)
print line
嗨拉胡爾,歡迎來到堆棧溢出。在某些情況下,您的代碼專用答案會更好;例如,如果您解釋了用於解決提問者問題的技術,那麼對於他們和尋找類似問題的答案的其他讀者來說,這將會更有用。 –
我更喜歡'line.split(':')[0]'。 – Matthias