Reading a portion of a file
Vulcanius
cmfvulcanius at gmail.com
Fri Mar 9 09:28:15 EST 2007
Here is the code I've come up with. Please feel free to critique it
and let me know what you would change. Also, as you can see I call
"open(SERVER,'r')" twice; but I want to only call it once, what would
the best way to do this be?
------------------------------------------------------------
import re
SERVER = "192.168.1.60"
# Pull all data from server file.
FILE = open(SERVER,'r')
ALLINFO = FILE.read()
# Grab a list of all sections in the server file.
SECTIONS = re.findall("(?m)^\#VS:\w*:.*:", ALLINFO)
# Remove duplicates from the list.
if SECTIONS:
SECTIONS.sort()
LAST = SECTIONS[-1]
for I in range(len(SECTIONS)-2, -1, -1):
if LAST==SECTIONS[I]: del SECTIONS[I]
else: LAST=SECTIONS[I]
# Pull data from each section and assign it a dictionary item.
# Data can be called using SECTIONDICT['section'] i.e
SECTIONDICT['df']
SECTIONDICT = {}
for SECT in SECTIONS:
PRESECTNAME1 = SECT[9:len(SECT) - 1]
PRESECTNAME2 = PRESECTNAME1.split("/")
SECTNAME = PRESECTNAME2[len(PRESECTNAME1.split("/")) - 1]
START = SECT + "START"
STOP = SECT + "STOP"
for LINE in open(SERVER,'r'):
LINE = LINE.strip()
if START in LINE:
SECTIONLISTTEMP = []
elif STOP in LINE:
SECTIONDICT[SECTNAME] = SECTIONLISTTEMP
SECTIONLISTTEMP = []
print "-" * 80
print "SECTION: %s" % SECTNAME
print SECTIONDICT[SECTNAME]
else:
if LINE:
SECTIONLISTTEMP.append(LINE)
FILE.close()
------------------------------------------------------------
More information about the Python-list
mailing list