gpt4 book ai didi

python - 如何在 Python 中将字符串包装到文件中?

转载 作者:IT老高 更新时间:2023-10-28 21:35:32 26 4
gpt4 key购买 nike

如何使用字符串的内容创建类似文件的对象(与 File 相同的鸭子类型)?

最佳答案

对于 Python 2.x,使用 StringIO模块。例如:

>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'

我使用 cStringIO(它更快),但请注意它不是 accept Unicode strings that cannot be encoded as plain ASCII strings . (您可以通过将“from cStringIO”更改为“from StringIO”来切换到StringIO。)

对于 Python 3.x,使用 io模块。

f = io.StringIO('foo')

关于python - 如何在 Python 中将字符串包装到文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/141449/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com