Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/python2....
File: StringIO.py
r"""File-like objects that read from or write to a string buffer.
[0] Fix | Delete
[1] Fix | Delete
This implements (nearly) all stdio methods.
[2] Fix | Delete
[3] Fix | Delete
f = StringIO() # ready for writing
[4] Fix | Delete
f = StringIO(buf) # ready for reading
[5] Fix | Delete
f.close() # explicitly release resources held
[6] Fix | Delete
flag = f.isatty() # always false
[7] Fix | Delete
pos = f.tell() # get current position
[8] Fix | Delete
f.seek(pos) # set current position
[9] Fix | Delete
f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
[10] Fix | Delete
buf = f.read() # read until EOF
[11] Fix | Delete
buf = f.read(n) # read up to n bytes
[12] Fix | Delete
buf = f.readline() # read until end of line ('\n') or EOF
[13] Fix | Delete
list = f.readlines()# list of f.readline() results until EOF
[14] Fix | Delete
f.truncate([size]) # truncate file at to at most size (default: current pos)
[15] Fix | Delete
f.write(buf) # write at current position
[16] Fix | Delete
f.writelines(list) # for line in list: f.write(line)
[17] Fix | Delete
f.getvalue() # return whole file's contents as a string
[18] Fix | Delete
[19] Fix | Delete
Notes:
[20] Fix | Delete
- Using a real file is often faster (but less convenient).
[21] Fix | Delete
- There's also a much faster implementation in C, called cStringIO, but
[22] Fix | Delete
it's not subclassable.
[23] Fix | Delete
- fileno() is left unimplemented so that code which uses it triggers
[24] Fix | Delete
an exception early.
[25] Fix | Delete
- Seeking far beyond EOF and then writing will insert real null
[26] Fix | Delete
bytes that occupy space in the buffer.
[27] Fix | Delete
- There's a simple test set (see end of this file).
[28] Fix | Delete
"""
[29] Fix | Delete
try:
[30] Fix | Delete
from errno import EINVAL
[31] Fix | Delete
except ImportError:
[32] Fix | Delete
EINVAL = 22
[33] Fix | Delete
[34] Fix | Delete
__all__ = ["StringIO"]
[35] Fix | Delete
[36] Fix | Delete
def _complain_ifclosed(closed):
[37] Fix | Delete
if closed:
[38] Fix | Delete
raise ValueError, "I/O operation on closed file"
[39] Fix | Delete
[40] Fix | Delete
class StringIO:
[41] Fix | Delete
"""class StringIO([buffer])
[42] Fix | Delete
[43] Fix | Delete
When a StringIO object is created, it can be initialized to an existing
[44] Fix | Delete
string by passing the string to the constructor. If no string is given,
[45] Fix | Delete
the StringIO will start empty.
[46] Fix | Delete
[47] Fix | Delete
The StringIO object can accept either Unicode or 8-bit strings, but
[48] Fix | Delete
mixing the two may take some care. If both are used, 8-bit strings that
[49] Fix | Delete
cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause
[50] Fix | Delete
a UnicodeError to be raised when getvalue() is called.
[51] Fix | Delete
"""
[52] Fix | Delete
def __init__(self, buf = ''):
[53] Fix | Delete
# Force self.buf to be a string or unicode
[54] Fix | Delete
if not isinstance(buf, basestring):
[55] Fix | Delete
buf = str(buf)
[56] Fix | Delete
self.buf = buf
[57] Fix | Delete
self.len = len(buf)
[58] Fix | Delete
self.buflist = []
[59] Fix | Delete
self.pos = 0
[60] Fix | Delete
self.closed = False
[61] Fix | Delete
self.softspace = 0
[62] Fix | Delete
[63] Fix | Delete
def __iter__(self):
[64] Fix | Delete
return self
[65] Fix | Delete
[66] Fix | Delete
def next(self):
[67] Fix | Delete
"""A file object is its own iterator, for example iter(f) returns f
[68] Fix | Delete
(unless f is closed). When a file is used as an iterator, typically
[69] Fix | Delete
in a for loop (for example, for line in f: print line), the next()
[70] Fix | Delete
method is called repeatedly. This method returns the next input line,
[71] Fix | Delete
or raises StopIteration when EOF is hit.
[72] Fix | Delete
"""
[73] Fix | Delete
_complain_ifclosed(self.closed)
[74] Fix | Delete
r = self.readline()
[75] Fix | Delete
if not r:
[76] Fix | Delete
raise StopIteration
[77] Fix | Delete
return r
[78] Fix | Delete
[79] Fix | Delete
def close(self):
[80] Fix | Delete
"""Free the memory buffer.
[81] Fix | Delete
"""
[82] Fix | Delete
if not self.closed:
[83] Fix | Delete
self.closed = True
[84] Fix | Delete
del self.buf, self.pos
[85] Fix | Delete
[86] Fix | Delete
def isatty(self):
[87] Fix | Delete
"""Returns False because StringIO objects are not connected to a
[88] Fix | Delete
tty-like device.
[89] Fix | Delete
"""
[90] Fix | Delete
_complain_ifclosed(self.closed)
[91] Fix | Delete
return False
[92] Fix | Delete
[93] Fix | Delete
def seek(self, pos, mode = 0):
[94] Fix | Delete
"""Set the file's current position.
[95] Fix | Delete
[96] Fix | Delete
The mode argument is optional and defaults to 0 (absolute file
[97] Fix | Delete
positioning); other values are 1 (seek relative to the current
[98] Fix | Delete
position) and 2 (seek relative to the file's end).
[99] Fix | Delete
[100] Fix | Delete
There is no return value.
[101] Fix | Delete
"""
[102] Fix | Delete
_complain_ifclosed(self.closed)
[103] Fix | Delete
if self.buflist:
[104] Fix | Delete
self.buf += ''.join(self.buflist)
[105] Fix | Delete
self.buflist = []
[106] Fix | Delete
if mode == 1:
[107] Fix | Delete
pos += self.pos
[108] Fix | Delete
elif mode == 2:
[109] Fix | Delete
pos += self.len
[110] Fix | Delete
self.pos = max(0, pos)
[111] Fix | Delete
[112] Fix | Delete
def tell(self):
[113] Fix | Delete
"""Return the file's current position."""
[114] Fix | Delete
_complain_ifclosed(self.closed)
[115] Fix | Delete
return self.pos
[116] Fix | Delete
[117] Fix | Delete
def read(self, n = -1):
[118] Fix | Delete
"""Read at most size bytes from the file
[119] Fix | Delete
(less if the read hits EOF before obtaining size bytes).
[120] Fix | Delete
[121] Fix | Delete
If the size argument is negative or omitted, read all data until EOF
[122] Fix | Delete
is reached. The bytes are returned as a string object. An empty
[123] Fix | Delete
string is returned when EOF is encountered immediately.
[124] Fix | Delete
"""
[125] Fix | Delete
_complain_ifclosed(self.closed)
[126] Fix | Delete
if self.buflist:
[127] Fix | Delete
self.buf += ''.join(self.buflist)
[128] Fix | Delete
self.buflist = []
[129] Fix | Delete
if n is None or n < 0:
[130] Fix | Delete
newpos = self.len
[131] Fix | Delete
else:
[132] Fix | Delete
newpos = min(self.pos+n, self.len)
[133] Fix | Delete
r = self.buf[self.pos:newpos]
[134] Fix | Delete
self.pos = newpos
[135] Fix | Delete
return r
[136] Fix | Delete
[137] Fix | Delete
def readline(self, length=None):
[138] Fix | Delete
r"""Read one entire line from the file.
[139] Fix | Delete
[140] Fix | Delete
A trailing newline character is kept in the string (but may be absent
[141] Fix | Delete
when a file ends with an incomplete line). If the size argument is
[142] Fix | Delete
present and non-negative, it is a maximum byte count (including the
[143] Fix | Delete
trailing newline) and an incomplete line may be returned.
[144] Fix | Delete
[145] Fix | Delete
An empty string is returned only when EOF is encountered immediately.
[146] Fix | Delete
[147] Fix | Delete
Note: Unlike stdio's fgets(), the returned string contains null
[148] Fix | Delete
characters ('\0') if they occurred in the input.
[149] Fix | Delete
"""
[150] Fix | Delete
_complain_ifclosed(self.closed)
[151] Fix | Delete
if self.buflist:
[152] Fix | Delete
self.buf += ''.join(self.buflist)
[153] Fix | Delete
self.buflist = []
[154] Fix | Delete
i = self.buf.find('\n', self.pos)
[155] Fix | Delete
if i < 0:
[156] Fix | Delete
newpos = self.len
[157] Fix | Delete
else:
[158] Fix | Delete
newpos = i+1
[159] Fix | Delete
if length is not None and length >= 0:
[160] Fix | Delete
if self.pos + length < newpos:
[161] Fix | Delete
newpos = self.pos + length
[162] Fix | Delete
r = self.buf[self.pos:newpos]
[163] Fix | Delete
self.pos = newpos
[164] Fix | Delete
return r
[165] Fix | Delete
[166] Fix | Delete
def readlines(self, sizehint = 0):
[167] Fix | Delete
"""Read until EOF using readline() and return a list containing the
[168] Fix | Delete
lines thus read.
[169] Fix | Delete
[170] Fix | Delete
If the optional sizehint argument is present, instead of reading up
[171] Fix | Delete
to EOF, whole lines totalling approximately sizehint bytes (or more
[172] Fix | Delete
to accommodate a final whole line).
[173] Fix | Delete
"""
[174] Fix | Delete
total = 0
[175] Fix | Delete
lines = []
[176] Fix | Delete
line = self.readline()
[177] Fix | Delete
while line:
[178] Fix | Delete
lines.append(line)
[179] Fix | Delete
total += len(line)
[180] Fix | Delete
if 0 < sizehint <= total:
[181] Fix | Delete
break
[182] Fix | Delete
line = self.readline()
[183] Fix | Delete
return lines
[184] Fix | Delete
[185] Fix | Delete
def truncate(self, size=None):
[186] Fix | Delete
"""Truncate the file's size.
[187] Fix | Delete
[188] Fix | Delete
If the optional size argument is present, the file is truncated to
[189] Fix | Delete
(at most) that size. The size defaults to the current position.
[190] Fix | Delete
The current file position is not changed unless the position
[191] Fix | Delete
is beyond the new file size.
[192] Fix | Delete
[193] Fix | Delete
If the specified size exceeds the file's current size, the
[194] Fix | Delete
file remains unchanged.
[195] Fix | Delete
"""
[196] Fix | Delete
_complain_ifclosed(self.closed)
[197] Fix | Delete
if size is None:
[198] Fix | Delete
size = self.pos
[199] Fix | Delete
elif size < 0:
[200] Fix | Delete
raise IOError(EINVAL, "Negative size not allowed")
[201] Fix | Delete
elif size < self.pos:
[202] Fix | Delete
self.pos = size
[203] Fix | Delete
self.buf = self.getvalue()[:size]
[204] Fix | Delete
self.len = size
[205] Fix | Delete
[206] Fix | Delete
def write(self, s):
[207] Fix | Delete
"""Write a string to the file.
[208] Fix | Delete
[209] Fix | Delete
There is no return value.
[210] Fix | Delete
"""
[211] Fix | Delete
_complain_ifclosed(self.closed)
[212] Fix | Delete
if not s: return
[213] Fix | Delete
# Force s to be a string or unicode
[214] Fix | Delete
if not isinstance(s, basestring):
[215] Fix | Delete
s = str(s)
[216] Fix | Delete
spos = self.pos
[217] Fix | Delete
slen = self.len
[218] Fix | Delete
if spos == slen:
[219] Fix | Delete
self.buflist.append(s)
[220] Fix | Delete
self.len = self.pos = spos + len(s)
[221] Fix | Delete
return
[222] Fix | Delete
if spos > slen:
[223] Fix | Delete
self.buflist.append('\0'*(spos - slen))
[224] Fix | Delete
slen = spos
[225] Fix | Delete
newpos = spos + len(s)
[226] Fix | Delete
if spos < slen:
[227] Fix | Delete
if self.buflist:
[228] Fix | Delete
self.buf += ''.join(self.buflist)
[229] Fix | Delete
self.buflist = [self.buf[:spos], s, self.buf[newpos:]]
[230] Fix | Delete
self.buf = ''
[231] Fix | Delete
if newpos > slen:
[232] Fix | Delete
slen = newpos
[233] Fix | Delete
else:
[234] Fix | Delete
self.buflist.append(s)
[235] Fix | Delete
slen = newpos
[236] Fix | Delete
self.len = slen
[237] Fix | Delete
self.pos = newpos
[238] Fix | Delete
[239] Fix | Delete
def writelines(self, iterable):
[240] Fix | Delete
"""Write a sequence of strings to the file. The sequence can be any
[241] Fix | Delete
iterable object producing strings, typically a list of strings. There
[242] Fix | Delete
is no return value.
[243] Fix | Delete
[244] Fix | Delete
(The name is intended to match readlines(); writelines() does not add
[245] Fix | Delete
line separators.)
[246] Fix | Delete
"""
[247] Fix | Delete
write = self.write
[248] Fix | Delete
for line in iterable:
[249] Fix | Delete
write(line)
[250] Fix | Delete
[251] Fix | Delete
def flush(self):
[252] Fix | Delete
"""Flush the internal buffer
[253] Fix | Delete
"""
[254] Fix | Delete
_complain_ifclosed(self.closed)
[255] Fix | Delete
[256] Fix | Delete
def getvalue(self):
[257] Fix | Delete
"""
[258] Fix | Delete
Retrieve the entire contents of the "file" at any time before
[259] Fix | Delete
the StringIO object's close() method is called.
[260] Fix | Delete
[261] Fix | Delete
The StringIO object can accept either Unicode or 8-bit strings,
[262] Fix | Delete
but mixing the two may take some care. If both are used, 8-bit
[263] Fix | Delete
strings that cannot be interpreted as 7-bit ASCII (that use the
[264] Fix | Delete
8th bit) will cause a UnicodeError to be raised when getvalue()
[265] Fix | Delete
is called.
[266] Fix | Delete
"""
[267] Fix | Delete
_complain_ifclosed(self.closed)
[268] Fix | Delete
if self.buflist:
[269] Fix | Delete
self.buf += ''.join(self.buflist)
[270] Fix | Delete
self.buflist = []
[271] Fix | Delete
return self.buf
[272] Fix | Delete
[273] Fix | Delete
[274] Fix | Delete
# A little test suite
[275] Fix | Delete
[276] Fix | Delete
def test():
[277] Fix | Delete
import sys
[278] Fix | Delete
if sys.argv[1:]:
[279] Fix | Delete
file = sys.argv[1]
[280] Fix | Delete
else:
[281] Fix | Delete
file = '/etc/passwd'
[282] Fix | Delete
lines = open(file, 'r').readlines()
[283] Fix | Delete
text = open(file, 'r').read()
[284] Fix | Delete
f = StringIO()
[285] Fix | Delete
for line in lines[:-2]:
[286] Fix | Delete
f.write(line)
[287] Fix | Delete
f.writelines(lines[-2:])
[288] Fix | Delete
if f.getvalue() != text:
[289] Fix | Delete
raise RuntimeError, 'write failed'
[290] Fix | Delete
length = f.tell()
[291] Fix | Delete
print 'File length =', length
[292] Fix | Delete
f.seek(len(lines[0]))
[293] Fix | Delete
f.write(lines[1])
[294] Fix | Delete
f.seek(0)
[295] Fix | Delete
print 'First line =', repr(f.readline())
[296] Fix | Delete
print 'Position =', f.tell()
[297] Fix | Delete
line = f.readline()
[298] Fix | Delete
print 'Second line =', repr(line)
[299] Fix | Delete
f.seek(-len(line), 1)
[300] Fix | Delete
line2 = f.read(len(line))
[301] Fix | Delete
if line != line2:
[302] Fix | Delete
raise RuntimeError, 'bad result after seek back'
[303] Fix | Delete
f.seek(len(line2), 1)
[304] Fix | Delete
list = f.readlines()
[305] Fix | Delete
line = list[-1]
[306] Fix | Delete
f.seek(f.tell() - len(line))
[307] Fix | Delete
line2 = f.read()
[308] Fix | Delete
if line != line2:
[309] Fix | Delete
raise RuntimeError, 'bad result after seek back from EOF'
[310] Fix | Delete
print 'Read', len(list), 'more lines'
[311] Fix | Delete
print 'File length =', f.tell()
[312] Fix | Delete
if f.tell() != length:
[313] Fix | Delete
raise RuntimeError, 'bad length'
[314] Fix | Delete
f.truncate(length/2)
[315] Fix | Delete
f.seek(0, 2)
[316] Fix | Delete
print 'Truncated length =', f.tell()
[317] Fix | Delete
if f.tell() != length/2:
[318] Fix | Delete
raise RuntimeError, 'truncate did not adjust length'
[319] Fix | Delete
f.close()
[320] Fix | Delete
[321] Fix | Delete
if __name__ == '__main__':
[322] Fix | Delete
test()
[323] Fix | Delete
[324] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function