>>>withopen('somefile', 'wt') as f: ... f.write('Hello\n') ... >>>withopen('somefile', 'xt') as f: ... f.write('Hello\n') ... Traceback (most recent call last): File "<stdin>", line 1, in <module> FileExistsError: [Errno 17] File exists: 'somefile'
5.6 字符串IO
使用 io.StringIO() 和 io.BytesIO() 类来创建类文件对象操作字符串数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
>>>s = io.StringIO() >>>s.write('Hello World\n') 12 >>>print('This is a test', file=s) 15 >>># Get all of the data written so far >>>s.getvalue() 'Hello World\nThis is a test\n' >>>
>>># Wrap a file interface around an existing string >>>s = io.StringIO('Hello\nWorld\n') >>>s.read(4) 'Hell' >>>s.read() 'o\nWorld\n'