I have a txt file that I want python to read, and from which I want python to extract a string specifically between two characters. Here is an example:
Line a
Line b
Line c
&TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST !
Line d
Line e
What I want is python to read the lines and when it encounters "&" I want it to start printing the lines (including the line with "$") up untill it encounters "!"
Any suggestions?
解决方案
This works:
data=[]
flag=False
with open('/tmp/test.txt','r') as f:
for line in f:
if line.startswith('&'):
flag=True
if flag:
data.append(line)
if line.strip().endswith('!'):
flag=False
print ''.join(data)
If you file is small enough that reading it all into memory is not an issue, and there is no ambiguity in & or ! as the start and end of the string you want, this is easier:
with open('/tmp/test.txt','r') as f:
data=''.join(f.readlines())
print data[data.index('&'):data.index('!')+1]
Or, if you want to read the whole file in but only use & and ! if they are are at the beginning and end of the lines respectively, you can use a regex:
import re
with open('/tmp/test.txt','r') as f:
data=''.join(f.readlines())
m=re.search(r'^(&.*!)\s*?\n',data,re.S | re.M)
if m: print m.group(1)