【问题标题】:Reading from StringIO without resetting position从 StringIO 读取而不重置位置
【发布时间】:2018-06-09 12:53:48
【问题描述】:

我有一个包含以下内容的测试代码:

with open('master.log') as f:
    print(f.read(8))
    print(f.read(8))

这打印为:

>> pi@raspberrypi:~/workspace/Program $ sudo python test.py
>> 12/29/20
>> 17 12:52

如您所见,这有不同的印刷品。但是,当我这样做时:

import cStringIO

stream= "1234567890"
print(cStringIO.StringIO(stream).read(8))
print(cStringIO.StringIO(stream).read(8))

当我运行它时,我得到以下输出:

>> pi@raspberrypi:~/workspace/Program $ sudo python test.py
>> 12345678
>> 12345678

在这种情况下,它输出相同的值(搜索器不前进)。

我需要这样做,以便 cStringIO(或类似的解决方案)以与文件相同的方式读取字符串。我的意思是每次读取都不会重置位置。

【问题讨论】:

  • 每次运行cStringIO.StringIO(stream) 时都会创建一个全新的 StringIO 对象。如果您两次使用相同的位置,则会保留该位置。

标签: python stringio cstringio


【解决方案1】:

正如@Michael Butscher 和其他人所逃避的那样,您需要创建流的实例。

>>> #import io                                      # python 3
>>> import cStringIO as io                          # python 2 
>>> stream = "1234567890"
>>> f = io.StringIO(stream)
>>> f.read(8)
'12345678'
>>> f.read(8)
'90'

【讨论】:

  • 可能会考虑import cStringIO as io,因此选择适当的import 行是唯一特定于版本的更改。此时,可以使用try/except ImportError 在它们之间切换。
  • 好主意。谢谢。
  • 我已经为此烦恼了很久。谢谢大家。
【解决方案2】:

你构造了一个StringIO 对象两次,这等于打开同一个文件两次。将对象分配给例如f并拨打f.read()两次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    相关资源
    最近更新 更多