【发布时间】:2015-10-07 04:25:01
【问题描述】:
我是编程新手。我创建了一个脚本,它遍历 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()
你能帮我解决这个问题吗?非常感谢!
【问题讨论】:
-
w+,类似于w,截断现有文件内容。 -
您实际上不需要一直打开文件。只需在循环前打开一次即可。