|
1 | | -# class StringIO implements file-like objects that read/write a |
2 | | -# string buffer (a.k.a. "memory files"). |
3 | | -# |
4 | | -# This implements (nearly) all stdio methods. |
5 | | -# |
6 | | -# f = StringIO() # ready for writing |
7 | | -# f = StringIO(buf) # ready for reading |
8 | | -# f.close() # explicitly release resources held |
9 | | -# flag = f.isatty() # always false |
10 | | -# pos = f.tell() # get current position |
11 | | -# f.seek(pos) # set current position |
12 | | -# f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF |
13 | | -# buf = f.read() # read until EOF |
14 | | -# buf = f.read(n) # read up to n bytes |
15 | | -# buf = f.readline() # read until end of line ('\n') or EOF |
16 | | -# list = f.readlines()# list of f.readline() results until EOF |
17 | | -# f.write(buf) # write at current position |
18 | | -# f.writelines(list) # for line in list: f.write(line) |
19 | | -# f.getvalue() # return whole file's contents as a string |
20 | | -# |
21 | | -# Notes: |
22 | | -# - Using a real file is often faster (but less convenient). |
23 | | -# - fileno() is left unimplemented so that code which uses it triggers |
24 | | -# an exception early. |
25 | | -# - Seeking far beyond EOF and then writing will insert real null |
26 | | -# bytes that occupy space in the buffer. |
27 | | -# - There's a simple test set (see end of this file). |
| 1 | +"""File-like objects that read from or write to a string buffer. |
| 2 | +
|
| 3 | +This implements (nearly) all stdio methods. |
| 4 | +
|
| 5 | +f = StringIO() # ready for writing |
| 6 | +f = StringIO(buf) # ready for reading |
| 7 | +f.close() # explicitly release resources held |
| 8 | +flag = f.isatty() # always false |
| 9 | +pos = f.tell() # get current position |
| 10 | +f.seek(pos) # set current position |
| 11 | +f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF |
| 12 | +buf = f.read() # read until EOF |
| 13 | +buf = f.read(n) # read up to n bytes |
| 14 | +buf = f.readline() # read until end of line ('\n') or EOF |
| 15 | +list = f.readlines()# list of f.readline() results until EOF |
| 16 | +f.write(buf) # write at current position |
| 17 | +f.writelines(list) # for line in list: f.write(line) |
| 18 | +f.getvalue() # return whole file's contents as a string |
| 19 | +
|
| 20 | +Notes: |
| 21 | +- Using a real file is often faster (but less convenient). |
| 22 | +- fileno() is left unimplemented so that code which uses it triggers |
| 23 | + an exception early. |
| 24 | +- Seeking far beyond EOF and then writing will insert real null |
| 25 | + bytes that occupy space in the buffer. |
| 26 | +- There's a simple test set (see end of this file). |
| 27 | +""" |
28 | 28 |
|
29 | 29 | import string |
30 | 30 |
|
|
0 commit comments