diff options
author | Greg Ward <gward@python.net> | 1999-03-26 21:48:59 (GMT) |
---|---|---|
committer | Greg Ward <gward@python.net> | 1999-03-26 21:48:59 (GMT) |
commit | 787451b65f7c9c93b0bbbac10819494c484c6501 (patch) | |
tree | b9cd2c713e5e81669b8353ebbe0fb4c520a4208a | |
parent | 447b4a06527ba1faa4aa0f963deb71a54f1a9a6a (diff) | |
download | cpython-787451b65f7c9c93b0bbbac10819494c484c6501.zip cpython-787451b65f7c9c93b0bbbac10819494c484c6501.tar.gz cpython-787451b65f7c9c93b0bbbac10819494c484c6501.tar.bz2 |
Added 'linestart' array and 'unreadline()' method (makes parsing a lot easier).
-rw-r--r-- | Lib/distutils/text_file.py | 31 |
1 files changed, 30 insertions, 1 deletions
diff --git a/Lib/distutils/text_file.py b/Lib/distutils/text_file.py index 6153dea..1d57956 100644 --- a/Lib/distutils/text_file.py +++ b/Lib/distutils/text_file.py @@ -52,6 +52,11 @@ class TextFile: self.filename = filename self.file = file self.current_line = 0 # assuming that file is at BOF! + + # 'linestart' stores the file offset of the start of each logical + # line; it is used to back up the file pointer when the caller + # wants to "unread" a line + self.linestart = [] def open (self, filename): @@ -81,6 +86,11 @@ class TextFile: buildup_line = '' while 1: + # record current file position; this will be appended to + # the linestart array *unless* we're accumulating a + # continued logical line + current_pos = self.file.tell() + # read the line, optionally strip comments line = self.file.readline() if self.strip_comments and line: @@ -101,6 +111,11 @@ class TextFile: self.current_line[1] = self.current_line[1] + 1 else: self.current_line = [self.current_line, self.current_line+1] + + # Forget current position: don't want to save it in the + # middle of a logical line + current_pos = None + # just an ordinary line, read it as usual else: if not line: @@ -111,7 +126,7 @@ class TextFile: self.current_line = self.current_line[1] + 1 else: self.current_line = self.current_line + 1 - + # strip whitespace however the client wants (leading and # trailing, or one or the other, or neither) @@ -128,6 +143,12 @@ class TextFile: if line == '' or line == '\n' and self.skip_blanks: continue + # if we're still here and have kept the current position, + # then this physical line starts a logical line; record its + # starting offset + if current_pos is not None: + self.linestart.append (current_pos) + if self.join_lines: if line[-1] == '\\': buildup_line = line[:-1] @@ -147,6 +168,14 @@ class TextFile: # end readline + def unreadline (self): + if not self.linestart: + raise IOError, "at beginning of file -- can't unreadline" + pos = self.linestart[-1] + del self.linestart[-1] + self.file.seek (pos) + + def readlines (self): lines = [] while 1: |