问题不在于pickle模块,而在于这行代码:
all_posts = previous_posts.extend(current_posts)
实际上发生的是
延伸
方法,扩展之前的_帖子,一旦成功完成就会返回关键字
没有一个
.
然后将该关键字分配给所有_帖子,而不是之前的_帖子的内容,然后将其写入文件。
尝试按如下方式修改它:
if new_post_count > 0:
file_name = 'all_posts' + user
previous_posts = pickle.load(open(file_name, 'rb'))
current_posts = get_posts(client, user, start_from_posts=0, total_posts=new_post_count)
previous_posts.extend(current_posts)
f = open(file_name, 'wb')
pickle.dump(previous_posts, f)
f.close()
最好包括让·弗朗索瓦的建议:
if new_post_count > 0:
file_name = 'all_posts' + user
with open(file_name, 'rb') as f:
previous_posts = pickle.load(f)
current_posts = get_posts(client, user, start_from_posts=0, total_posts=new_post_count)
previous_posts.extend(current_posts)
with open(file_name, 'wb') as f:
pickle.dump(previous_posts, f)