【问题标题】:writing json stream to file limits output size将 json 流写入文件限制输出大小
【发布时间】:2014-06-18 23:55:50
【问题描述】:

所以我正在使用 twython(EDIT: python Twitter 客户端库)编写一个简单的 python 流侦听器,当运行 .py 时,输出文件大小在 1 到 5kb 之间波动。我想知道如何确保文件不断被写入。下面是代码。

class MyStreamer(TwythonStreamer):
def on_success(self, data):
    with open(filename,'w')as outfile:
        json.dump(data,outfile,indent=4)
        outfile.flush()
        outfile.close()

    def on_error(self, status_code, data):
    print(status_code)

stream = MyStreamer(APP_KEY, APP_SECRET,
                OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
stream.statuses.filter(track=input_string)

【问题讨论】:

  • 为什么每次写入的数据都要以相同的大小开头?您怎么知道您每次都读取相同的数据?您是否尝试在on_success 函数中添加print(data) 或其他调试语句来检查此假设?
  • 您是在问如何附加到文件而不是覆盖它?打开文件时使用模式a 而不是w。但是文件中的 JSON 字符串序列不是有效的 JSON 文件,所以这可能不是一个好主意。
  • @Dan ,在流式传输时,输出文件大小会在几秒钟内发生变化(即 1、2、3、1、2、1 kb 等)。没有严格增加尺寸。
  • @Diabellical,为什么这种行为出乎意料?如果您从 Twitter 流式传输大量数据,那么您获得的数据量将发生不可预测的变化。输出文件的大小正在发生变化,因为您每次都完全覆盖它

标签: python json twitter streaming twython


【解决方案1】:

您的问题没有得到很清楚的解释,但基于上面的 cmets,我认为您对输出文件不断被覆盖的事实感到困惑......而不是随着新数据的添加而增长。

问题是您的open(filename,'w') 每次通过时都会覆盖文件。请尝试这样做:

# global outfile 
outfile = open(filename,'w')

class MyStreamer(TwythonStreamer):
    def on_success(self, data):
        json.dump(data,outfile,indent=4)
        outfile.flush()

        def on_error(self, status_code, data):
            print(status_code)

stream = MyStreamer(APP_KEY, APP_SECRET,
                OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
stream.statuses.filter(track=input_string)

# when you are actually done writing output to it:
# outfile.close()

请注意,这种方法不会生成有效的 JSON 文件,因为您只是将多个 JSON 块连接在一起。但这是一个单独的问题。 JSON 最初并不是一种“流式”格式,而是see this thread for some discussion

【讨论】:

  • 感谢您的指导。我是编程和 python 的新手。这非常有效。再次感谢。
猜你喜欢
  • 2011-08-31
  • 2016-08-03
  • 2011-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-12
  • 2018-05-25
相关资源
最近更新 更多