Reading a portion of a file

Rune Strand rune.strand at gmail.com
Thu Mar 8 11:52:48 EST 2007


On Mar 8, 5:12 pm, cmfvulcan... at gmail.com wrote:
> I am using a script with a single file containing all data in multiple
> sections. Each section begins with "#VS:CMD:command:START" and ends
> with "#VS:CMD:command:STOP". There is a blank line in between each
> section. I'm looking for the best way to grab one section at a time.
> Will I have to read the entire file to a string and parse it further
> or is it possible to grab the section directly when doing a read? I'm
> guessing regex is the best possible way. Any help is greatly
> appreciated.

Seems like something along these line will do:

_file_ = "filepart.txt"

begin_tag = '#VS:CMD:command:START'
end_tag = '#VS:CMD:command:STOP'

sections = []
new_section = []
for line in open(_file_):
    line = line.strip()
    if begin_tag in line:
        new_section = []
    elif end_tag in line:
        sections.append(new_section)
    else:
        if line: new_section.append(line)

for s in sections: print s

If your want more control, perhaps flagging "inside_section",
"outside_section" is an idea.





More information about the Python-list mailing list