簡體   English   中英

將json流寫入文件以限制輸出大小

[英]writing json stream to file limits output size

因此,我正在使用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)

您的問題沒有得到很清楚的解釋,但是基於以上評論,我認為您對輸出文件不斷被覆蓋的事實感到困惑...而不是在向其添加新數據時不斷增長。

問題是您的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並非一開始就打算成為“流”格式,但請參見此主題進行一些討論

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM