如何在Python中将字符串写入文件?
我该如何创建一个像文件一样的对象(和文件的特性相同),并且里面的内容是一个字符串呢?
4 个回答
14
如果你的文件对象是用来处理字节数据的,那么在使用之前,字符串需要先转换成字节格式。接着,你可以使用一个叫做 BytesIO 的对象来代替。下面是Python 3中的示例:
from io import BytesIO
string_repr_of_file = 'header\n byline\n body\n body\n end'
function_that_expects_bytes(BytesIO(bytes(string_repr_of_file,encoding='utf-8')))
49
在Python 3.0中:
import io
with io.StringIO() as f:
f.write('abcdef')
print('gh', file=f)
f.seek(0)
print(f.read())
输出结果是:
'abcdefgh'
163
对于Python 2.x版本,可以使用StringIO模块。比如说:
>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'
我使用的是cStringIO(因为它更快),但要注意,它不支持那些不能被编码为普通ASCII字符串的Unicode字符串。如果你想使用StringIO,只需要把“from cStringIO”改成“from StringIO”就可以了。
对于Python 3.x版本,使用io
模块。
f = io.StringIO('foo')