python - 不能在 StringIO 中使用 readline()
问题描述
我想将字符串写入 StringIO() 对象,然后逐行读取;我尝试了两种方法,但都没有产生任何输出。我究竟做错了什么?
创建对象,写入它并检查它是否有效:
from io import StringIO
temp=StringIO()
temp.write("This is a \n test sentence\n!")
temp.getvalue() --> 'This is a \n test sentence\n!'
方法一:
for line in temp:
print(line)
方法二:
test = True
while test:
line = temp.readline()
if not line:
test=False
else:
print(line)
解决方案
您必须将( seek
) 流位置更改为字节偏移量0
。您还可以使用tell
来获取当前流位置。
>>> from io import StringIO
>>> temp = StringIO()
>>> temp.write("This is a \n test sentence\n!")
27
>>> temp.tell() # current stream position.
27
>>> temp.seek(0) # Change the stream position to the byte offset `0`
0
>>> for line in temp:
... print(line)
...
This is a
test sentence
!
推荐阅读
- javascript - React - 仅更新被点击元素的状态
- dart - 如何在构造函数中将常量值分配为默认值
- javascript - 使用reduce返回具有每个对象值总和的新对象数组
- json - React:在动态输入字段中动态添加输入字段
- shopify - 使用 shopify checkout api 创建自定义结帐
- flutter - Flutter 中的状态可以调用自身吗?
- python-sphinx - 警告:点命令 dot 无法运行
- angular - Gitlab CI 为 Angular 应用程序获取“[Launcher]:您的平台上的 Chrome 浏览器没有二进制文件”
- java - 如何在 build.gradle 文件中导入 java 类
- identityserver4 - IdentityServer4:将过期日期设置为“idsrv.session”cookie