diff options
author | Fred Drake <fdrake@acm.org> | 2000-09-28 04:21:06 (GMT) |
---|---|---|
committer | Fred Drake <fdrake@acm.org> | 2000-09-28 04:21:06 (GMT) |
commit | e0a7f4f9d52acd8fccaa80fd9976325748f6b070 (patch) | |
tree | 89a77223df71598eeba801d83069fde12f91c427 | |
parent | d391a349262848e368498f4653992ae24fee5b39 (diff) | |
download | cpython-e0a7f4f9d52acd8fccaa80fd9976325748f6b070.zip cpython-e0a7f4f9d52acd8fccaa80fd9976325748f6b070.tar.gz cpython-e0a7f4f9d52acd8fccaa80fd9976325748f6b070.tar.bz2 |
Add truncate() method to StringIO objects.
This closes SourceForge bug #115527.
-rw-r--r-- | Lib/StringIO.py | 13 |
1 files changed, 13 insertions, 0 deletions
diff --git a/Lib/StringIO.py b/Lib/StringIO.py index 02eb7c8..334bf85 100644 --- a/Lib/StringIO.py +++ b/Lib/StringIO.py @@ -13,6 +13,7 @@ buf = f.read() # read until EOF buf = f.read(n) # read up to n bytes buf = f.readline() # read until end of line ('\n') or EOF list = f.readlines()# list of f.readline() results until EOF +f.truncate([size]) # truncate file at to at most size (default: current pos) f.write(buf) # write at current position f.writelines(list) # for line in list: f.write(line) f.getvalue() # return whole file's contents as a string @@ -28,6 +29,7 @@ Notes: - There's a simple test set (see end of this file). """ +import errno import string class StringIO: @@ -102,6 +104,17 @@ class StringIO: break line = self.readline() return lines + def truncate(self, size=None): + if self.closed: + raise ValueError, "I/O operation on closed file" + if size is None: + size = self.pos + elif size < 0: + raise IOError(errno.EINVAL, + "Negative size not allowed") + elif size < self.pos: + self.pos = size + self.buf = self.getvalue()[:size] def write(self, s): if self.closed: raise ValueError, "I/O operation on closed file" |