为什么我的文本文件不断覆盖其中的数据? [英] Why does my my text file keep overwriting the data on it?

查看:99
本文介绍了为什么我的文本文件不断覆盖其中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从产品的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方法

的内容

可以这样做

修改:

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:

2

那是它的值被覆盖了

a追加到现有文件

i.e)

File1.txt:

123

代码:

with open("File1.txt","a") as oup1:
    oup1.write("2")

python运行后

File1.txt:

1232

书面内容附在末尾

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?

解决方案

This use to using file operator with w mode you are overwriting the content you can use a append method

It can be done like this

Modification:

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

w overwrites on the existing file

i.e)

File1.txt:

123

code:

with open("File1.txt","w") as oup1:
    oup1.write("2")

File1.txt after python run:

2

That is it's value is overwritten

a appends to the existing file

i.e)

File1.txt:

123

code:

with open("File1.txt","a") as oup1:
    oup1.write("2")

File1.txt after python run:

1232

The written content is appended to the end

这篇关于为什么我的文本文件不断覆盖其中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆