【问题标题】:need string or buffer, file found需要字符串或缓冲区,找到文件
【发布时间】:2026-01-15 15:50:01
【问题描述】:

我应该在文件中保留一个偏移量并读取该偏移量行并发出,更新偏移量 = 偏移量 + 1

class SimSpout(storm.Spout):

  # Not much to do here for such a basic spout
  def initialize(self, conf, context):
    ## Open the file with read only permit
    self.f = open('data.txt', 'r')
    ## Read the first line
    self._conf = conf
    self._context = context
    self._offset = 0
    storm.logInfo("Spout instance starting...")

 # Process the next tuple
 def nextTuple(self):
    # check if it reach at the EOF to close it
    with open(self.f) as f:
      f.readlines()[self._offset]
      #Emit a random sentence
      storm.logInfo("Emiting %s" % line)
      storm.emit([line])
    self._offset = self._offset + 1

但我有错误

with open(self.f) as f:
TypeError: coercing to Unicode: need string or buffer, file found

【问题讨论】:

    标签: python python-2.7 apache-storm


    【解决方案1】:

    你在这一行打开一个文件

    self.f = open('data.txt', 'r')
    

    并尝试打开文件句柄而不是此行中的同一文件

    with open(self.f) as f:
    

    相反,在nextTuple 中,只需使用self.f 而不是f

    【讨论】:

    • 感谢您的回复,但请原谅我是 python 新手。你的意思是这样写 open(self.f): self.f.readlines()[self._offset] ?
    • 你还在吗?