Without the call to
seek
,
the
write
would overwrite the existing contents of
lines
.
import sys import io lines = io.StringIO(initial_value = "line 1\n") for i, cls in enumerate(type(lines).mro(), start = 1): print(i, cls) print() lines.seek(0, io.SEEK_END) #Wind to the end of the file. n = lines.write("line 2\n") print(f"Wrote {n} characters.") print() print("line 3", file = lines) #print supplies a trailing "\n" oneBigString = lines.getvalue() lines.close() print(oneBigString) sys.exit(0)
1 <class '_io.StringIO'> 2 <class '_io._TextIOBase'> 3 <class '_io._IOBase'> 4 <class 'object'> Wrote 7 characters. line 1 line 2 line 3
print(oneBigString)to
for i, line in enumerate(oneBigString.splitlines(), start = 1): print(i, line)or insert the following code before the
close
.
lines.seek(0, io.SEEK_SET) #Rewind the file back to the beginning. for line in enumerate(lines, start = 1): print(line, end = "")
1 line 1 2 line 2 3 line 3
io.StringIO
by taking advantage of the fact that the
io.StringIO
is a
context
manager.