Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e0a7f4f

Browse files
committed
Add truncate() method to StringIO objects.
This closes SourceForge bug #115527.
1 parent d391a34 commit e0a7f4f

1 file changed

Lines changed: 13 additions & 0 deletions

File tree

Lib/StringIO.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
buf = f.read(n) # read up to n bytes
1414
buf = f.readline() # read until end of line ('\n') or EOF
1515
list = f.readlines()# list of f.readline() results until EOF
16+
f.truncate([size]) # truncate file at to at most size (default: current pos)
1617
f.write(buf) # write at current position
1718
f.writelines(list) # for line in list: f.write(line)
1819
f.getvalue() # return whole file's contents as a string
@@ -28,6 +29,7 @@
2829
- There's a simple test set (see end of this file).
2930
"""
3031

32+
import errno
3133
import string
3234

3335
class StringIO:
@@ -102,6 +104,17 @@ def readlines(self, sizehint = 0):
102104
break
103105
line = self.readline()
104106
return lines
107+
def truncate(self, size=None):
108+
if self.closed:
109+
raise ValueError, "I/O operation on closed file"
110+
if size is None:
111+
size = self.pos
112+
elif size < 0:
113+
raise IOError(errno.EINVAL,
114+
"Negative size not allowed")
115+
elif size < self.pos:
116+
self.pos = size
117+
self.buf = self.getvalue()[:size]
105118
def write(self, s):
106119
if self.closed:
107120
raise ValueError, "I/O operation on closed file"

0 commit comments

Comments
 (0)