[Tutor] Parsing text file
Alan
python at wardroper.org
Mon May 14 00:04:36 CEST 2007
I'm looking for a more elegant way to parse sections of text files that
are bordered by BEGIN/END delimiting phrases, like this:
some text
some more text
BEGIN_INTERESTING_BIT
someline1
someline2
someline3
END_INTERESTING_BIT
more text
more text
What I have been doing is clumsy, involving converting to a string and
slicing out the required section using split('DELIMITER'):
import sys
infile = open(sys.argv[1], 'r')
#join list elements with @ character into a string
fileStr = '@'.join(infile.readlines())
#Slice out the interesting section with split, then split again into
lines using @
resultLine =
fileStr.split('BEGIN_INTERESTING_BIT')[1].split('END_INTERESTING_BIT')[0].split('@')
for line in resultLine:
do things
Can anyone point me at a better way to do this?
Thanks
--
--------------------------
Alan Wardroper
alan at wardroper.org
More information about the Tutor
mailing list