[英]Pickle (Python 3.6) Writes Empty File
我正在嘗試自學Python,因此創建了一個啞腳本,用於檢查博客網站以檢查新更新,然后保存與更新關聯的元數據。 如果有新帖子,我將打開以前的元數據,附加新的元數據,然后保存。 但是,我發現很多時候(無法弄清它什么時候起作用,什么時候不起作用),這些更新會產生一個空文件,並且我丟失了所有元數據。
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)
all_posts = previous_posts.extend(current_posts)
f = open(file_name, 'wb')
pickle.dump(all_posts, f)
f.close()
在論壇上,除泡菜外,使用其他方法保存我的數據可能更有意義(有什么建議嗎?)。 即使是這種情況,我仍然想知道我在這里做錯了什么,所以以后就不會再犯同樣的錯誤了。
問題不在於pickle模塊,而是如下行:
all_posts = previous_posts.extend(current_posts)
實際發生的是調用了extend方法,在原地擴展了previous_posts,一旦成功完成,它將返回關鍵字None 。
然后,您可以將此關鍵字分配給all_posts而不是previous_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()
更好的是包括Jean-Francois的建議:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.