Sample StringIO usage of python module

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

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 the file object and StringIO are mostly the same, read, readline, readlines, write, writelines are all available, StringIO can be conveniently used 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 an c language version with better performance, but with a slight difference, cStringIO doesn't have len or pos properties.


Related articles: