将推文保存在文件中,但它们被 Python 覆盖

Saving tweets in a file, but they are overwritten by Python

我是编程新手。我创建了一个脚本,循环遍历 twitter id 列表,检索它们的时间线并将它们保存在 json 存档中。但是,我认为每次使用最后一个时间线并覆盖文件并只保留最后一个。

这是我的循环代码:

idfile = open('ids_part1.txt', 'r+')
for id in idfile:
    if id:
        id = id.strip()
        try:
            result = ret_timeline(user_id=id)
            if result:
                result_file = open('result1.json', 'w+')
                for st in result:
                    result_file.write(json.dumps(st._json, indent=4, sort_keys=True))
                result_file.close()

你能帮我吗?非常感谢你!

您需要以追加模式打开文件,应该没问题

result_file = open('result1.json', 'a')