[英]Python: Modifying text file after certain character
我正在使用python對文本文件進行一些操作。 但是有一件事我還找不到解決方案。 我希望這里有人可以幫助我。
在該文本文件的每一行中,我都有單詞order
,然后有一個由,
和數字組成的各種字符串。
現在,我想刪除單詞order
以及該行中的所有內容,但是我找不到方法。 文件中聲明order
的位置總是變化的,因此我無法指向某個位置並隨后刪除所有內容。
因為只刪除文本的一部分,所以做您想做的事情非常容易,因此您可以使用“ r +”模式在您讀取的同一文件中進行重寫。
with open(filename,'r+') as fr,open(filename,'r+') as fw:
for line in fr:
x = line.find('order')
fw.write(line if x==-1
else line[0:x]+'\n' if '\n' in line
else line[0:x])
fw.truncate()
如果文件不太大,可以完全讀取並保存在RAM中,這是使用正則表達式的另一種方法:
import re
r = re.compile('(.*?)(?:order.*?$|\Z)',
re.MULTILINE|re.DOTALL)
with open(filename,'r+') as f:
x = f.read()
f.seek(0,0)
f.write(''.join(r.findall(x)))
f.truncate()
逐行遍歷文件(我假設您已經在執行此操作),然后使用string.find
:
>>> import string
>>> x = 'helloORDERme'
>>> string.find(x,"ORDER")
5
>>> x[:string.find(x,"ORDER")]
'hello'
或者,如果您真的還需要知道這一點:
import string
with open('myfile', 'rU') as f:
for line in f:
print line[:string.find(line,"order")]
我將寫回更新的值作為練習者的練習。
lines = "hello1OrderABC\nhello2OrderDEF".splitlines()
for line in lines:
print line[:line.find("Order")]
------
hello1
hello2
第一行創建行列表['hello1OrderABC','hello2OrderDEF']。 其余的遍歷此列表並打印出所有內容,直到單詞“ Order”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.