为什么我的文本文件会不断覆盖上面的数据? [英] Why does my text file keep overwriting the data on it?
问题描述
我试图从产品的Facebook页面中提取一些数据并将其全部转储到文本文件中,但是我发现该文件不断被数据覆盖.我不确定这是一个分页问题还是必须制作多个文件.
I'm trying to pull some data from Facebook pages for a product and dump it all into a text file, but I find that the file keeps overwriting itself with the data. I'm not sure if it's a pagination issue or if I have to make several files.
这是我的代码:
#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)
关于为什么发生这种情况的任何想法吗?
Any idea as to why this is happening?
推荐答案
这是因为您在w
模式下使用文件运算符,所以您正在覆盖内容.您可以使用a
附加模式:
This is because you are using the file operator with w
mode, you are overwriting the content. You can use the a
append mode:
可以这样做
修改:
with open('test121.txt', 'w') as outfile:
while True:
posts = requests.get(posts['paging']['next']).json()
json.dump(posts, outfile)
w
覆盖现有文件
i.e)
File1.txt:
123
代码:
with open("File1.txt","w") as oup1:
oup1.write("2")
python运行后
File1.txt:
File1.txt after python run:
2
其值被覆盖
a
追加到现有文件中
i.e)
File1.txt:
123
代码:
with open("File1.txt","a") as oup1:
oup1.write("2")
python运行后
File1.txt:
File1.txt after python run:
1232
书面内容附在末尾.
这篇关于为什么我的文本文件会不断覆盖上面的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!