Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...