The Python StringIO module implements reading and writing data in the memory buffer

  • 2020-05-05 11:28:20
  • OfStack

The module is written in a class, and there is only one StringIO class, so its available methods are in the class.
Most of the functions in this class are similar to what you would do to a file.

Example:


#coding=gbk
 
import StringIO, cStringIO, sys
 
s = StringIO.StringIO("JGood is a handsome boy")
s.write("JGood is a handsome boy \r\n")
s.write('okkkk China ')
s.seek(0)
print s.read()
 
# The last 4 bytes
s.seek(-4, 2)
print s.read()
 
#---- The results of ----
#JGood is a handsome boy
#okkkk China
# China

 

Through the example, we can see the behavior of StringIO, which is basically the same as file. StringIO provides a method to easily retrieve the data: StringIO.getvalue (). If you use the read method to get the data in it, you must first set the location of the "file pointer" through seek.

There is also an cStringIO module available in the Python standard module, which behaves roughly the same as StringIO, but runs better than StringIO. However, there are a few points to note when using the cStringIO module: 1. cStringIO.StringIO cannot be inherited as a base class; 2. 2. When an cStringIO.StringIO object is created, the newly generated object is read-only if the initialization data is provided by the initialization function. So the following code is wrong: s = cStringIO.StringIO ("JGood/n"); OOOKKK s. write (" ");

----------------------


s=StringIO.StrngIO([buf])

This instance is similar to the open method, except that it does not generate files on the hard disk, but only stores them in the buffer. The optional parameter buf is an str or unicode type. It will be stored with other subsequent writes.
----------------------
Methods in the StringIO class:
low read
Low readline
Low readlines
Low write
Low writelines
Low getvalue
Low truncate
Low tell
Low seek
Low close
Low isatty
Low flush
----------------------
s.read([n])
Parameter n limits the read length, int type; The default is to read all data stored in object s from the current read/write location. After the read, the read position is moved.
----------------------
s.readline([length])
Parameter length defines the end of the read, int type, None by default: read from the current read and write position to the next one ending with "\n". The read/write position is moved.
----------------------
s.readlines([sizehint])
The sizehint parameter is of type int, and by default reads all rows and returns them as a list, in addition to reading from the current read/write position until the next row ends with "\n". The read/write position is moved.
----------------------
s.write(s)
Writes the parameter s from the read/write position to the object s. The parameter s is of type str or unicode. The read/write position is moved.
----------------------
s.writelines(list)
Write list to the object s from the read/write position. The parameter list is a list with members of str or unicode types. The read/write position is moved.
----------------------
s.getvalue()
This function takes no arguments and returns all data in the object s.
----------------------
s.truncate([size])
Cut off the data from the read/write position. The parameter size limits the clipping length. The default value is None.
----------------------
s.tell()
Returns the current read/write position.
----------------------
s.seek(pos[,mode])
Move the current read and write position to pos. When the optional parameter mode is 0, move the read and write position to pos. The default is 0.
----------------------
s.close()
The buffer is released. After this function is executed, the data is released and cannot be manipulated again.
---------------------
s.isatty()
This function always returns 0. Whether or not the StringIO object has been close().
----------------------
s.flush()
Flush the internal buffer.
----------------------
The return value of dir(StringIO.StringIO) also contains an test function, but ignore it, it makes no sense to

=====================================================

StringIO is often used as a cache of strings, because StringIO has the advantage that some of its interfaces are consistent with file operations, meaning that with the same code, it can be used both as a file operation and as an StringIO operation. For example:


import string, os, sys
import StringIO def writedata(fd, msg):
    fd.write(msg)
   
f = open('aaa.txt', 'w') writedata(f, "xxxxxxxxxxxx")
f.close() s = StringIO.StringIO()
writedata(s, "xxxxxxxxxxxxxx")

Since file objects and StringIO are mostly the same, read, readline, readlines, write, writelines are all available, StringIO is very handy as an "in-memory file object."


  import string
import StringIO s = StringIO.StringIO()
s.write("aaaa")
lines = ['xxxxx', 'bbbbbbb']
s.writelines(lines) s.seek(0)
print s.read() print s.getvalue()
s.write(" ttttttttt ")
s.seek(0)
print s.readlines()
print s.len

StringIO also has a corresponding c language version with better performance, but with a slight difference, cStringIO does not have len or pos properties. (also, cStringIO does not support Unicode encoding)


Related articles: