[BangPypers] [Novice] Question on File seek and tell methods
saurabh
saurabh.hirani at gmail.com
Mon Jun 17 14:58:57 CEST 2013
Well, if you must do it that way then this is what I cooked up in a hurry.
See if you like it. It comes with the caveat of recording the first
pattern's pos and re-reading the file from that pos again.
#!/usr/bin/env python
import re
import sys
# not doing input validation
# call program as: python prog.py start_keyword stop_keyword file_to_read
start_pattern = sys.argv[1]
stop_pattern = sys.argv[2]
inputfile = sys.argv[3]
re_start_pattern = re.compile(r'^%s$' % (start_pattern))
re_stop_pattern = re.compile(r'^%s$' % (stop_pattern))
pattern = re_start_pattern
last_line_len = 0
# this function should have a better name + check it for corner cases
def patternized_read(filename, pattern, printlines = False, start_at = 0):
matched = False
with open(inputfile) as f:
f.seek(start_at, 0)
pattern_pos = 0
line = f.readline()
while line:
if printlines:
print line
match = re.search(pattern, line)
# if the pattern matches
if (match):
matched = True
break
pattern_pos = f.tell()
line = f.readline()
if matched:
return pattern_pos
return None
start_pos = patternized_read(inputfile, re_start_pattern)
if start_pos is None:
print "start pattern %s is not present" % (start_pattern)
sys.exit(1)
end_pos = patternized_read(inputfile, re_stop_pattern, printlines = True,
start_at = start_pos)
--
View this message in context: http://python.6.x6.nabble.com/Novice-Question-on-File-seek-and-tell-methods-tp5021174p5021560.html
Sent from the Bangalore (BangPypers) mailing list archive at Nabble.com.
More information about the BangPypers
mailing list