Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

python - Why does my text file keep overwriting the data on it?

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.

Here's my code:

#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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

w overwrites, open with a to append or open the file once outside the loop:

append:

while True:
    posts = requests.get(posts['paging']['next']).json()
    #print posts
    with open('test121.txt', 'a') as outfile:
        json.dump(posts, outfile)

Open once outside the loop:

with open('test121.txt', 'w') as outfile:
    while True:
        posts = requests.get(posts['paging']['next']).json()
        #print posts
        json.dump(posts, outfile)

It makes more sense to use the second option, if you are going to be running the code multiple times then you can open with a outside the loop also, if the file does not exist it will be created, if it does data will be appended


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...