将JSON流写入文件时限制输出大小

0 投票
1 回答
1963 浏览
提问于 2025-04-18 10:18

我正在用twython(编辑:一个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)

1 个回答

0

你的问题没有解释得很清楚,但根据上面的评论,我觉得你可能搞混了输出文件总是被覆盖,而不是像你想的那样不断增加新数据。

问题在于你使用的 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本身并不是为了“流式”格式设计的,可以看看这个讨论

撰写回答