我试图从产品的 Facebook 页面中提取一些数据并将其全部转储到文本文件中,但我发现该文件不断用数据覆盖自身。我不确定这是分页问题还是我必须制作多个文件。
这是我的代码:
#Modules
import requests
import facebook
import json
def some_action(post):
print posts['data']
print post['created_time']
#Token
access_token = 'INSERT ACCESS TOKEN'
user = 'walkers'
#Posts
graph = facebook.GraphAPI(access_token)
profile = graph.get_object(user)
posts = graph.get_connections(profile['id'], 'posts')
#Write
while True:
posts = requests.get(posts['paging']['next']).json()
#print posts
with open('test121.txt', 'w') as outfile:
json.dump(posts, outfile)
知道为什么会发生这种情况吗?
w
覆盖,打开方式a
在循环外追加或打开文件:
append:
while True:
posts = requests.get(posts['paging']['next']).json()
#print posts
with open('test121.txt', 'a') as outfile:
json.dump(posts, outfile)
在循环外打开一次:
with open('test121.txt', 'w') as outfile:
while True:
posts = requests.get(posts['paging']['next']).json()
#print posts
json.dump(posts, outfile)
使用第二个选项更有意义,如果您要多次运行代码,则可以使用以下命令打开a
在循环之外,如果文件不存在,则会创建该文件,如果存在,则会追加数据
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)