簡體   English   中英

如何將此代碼的輸出寫入文本文件?

[英]How to write this code's output to a text file?

我只想要文本文件中的所有輸出

def load_comments(self, mat):


    for item in mat["items"]:
        comment = item["snippet"]["topLevelComment"]
        author = comment["snippet"]["authorDisplayName"]
        text = comment["snippet"]["textDisplay"]

        if 'replies' in item.keys():
            for reply in item['replies']['comments']:
                rauthor = reply['snippet']['authorDisplayName']
                rtext = reply["snippet"]["textDisplay"]
            print("{}".format(rtext))
        print("{}".format(text))

當我嘗試在運行代碼時簡單地放置 >filename.txt 時,它只打印一些行而不是所有行。 但是當我嘗試在控制台上運行它時,它會打印所有評論。

假設輸出是這部分:

print("{}".format(text))

只需將其替換為:

with open('filename.txt', 'w+') as file:
    file.write("{}".format(text))

暫無
暫無

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

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