python - How to grab a chunk of data from a file? -
i want grab chunk of data file. know start line , end line. wrote code incomplete , don't know how solve further.
file = open(filename,'r') end_line='### leave comment!' star_line = 'kill master' line in file: if star_line in line: ??
startmarker = "ohai" endmarker = "meheer?" marking = false result = [] open("somefile") f: line in f: if line.startswith(startmarker): marking = true elif line.startswith(endmarker): marking = false if marking: result.append(line) if len(result) > 1: print "".join(result[1:])
explanation: with
block nice way use files -- makes sure don't forget close()
later. for
walks each line and:
- starts outputting when sees line starts
'ohai'
(including line) - stops outputting when sees line starts
'meheer?'
(without outputting line).
after loop, result
contains part of file needed, plus initial marker. rather making loop more complicated ignore marker, throw out using slice: result[1:]
returns elements in result
starting @ index 1; in other words, excludes first element (index 0).
update reflect add partial-line matches:
startmarker = "ohai" endmarker = "meheer?" marking = false result = [] open("somefile") f: line in f: if not marking: index = line.find(startmarker) if index != -1: marking = true result.append(line[index:]) else: index = line.rfind(endmarker) if index != -1: marking = false result.append(line[:index + len(endmarker)]) else: result.append(line) print "".join(result)
yet more explanation: marking
still tells whether should outputting whole lines, i've changed if
statements start , end markers follows:
if we're not (yet) marking, , see
startmarker
, output current line starting @ marker.find
method returns position of first occurrence ofstartmarker
in case.line[index:]
notation means 'the content ofline
starting @ positionindex
.while marking, output current line entirely unless contains
endmarker
. here, userfind
find rightmost occurrence ofendmarker
, ,line[...]
notation means 'the content ofline
positionindex
(the start of match) plus marker itself.' also: stop marking :)
Comments
Post a Comment