Python-将变量写入文本文件 [英] Python - writing a variable to a text file

查看:380
本文介绍了Python-将变量写入文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是我对Python和Raspberry Pi进行编程的第一次尝试.我的小项目是当我在Twitter上被提及时点亮一个LED.一切都非常简单,下面显示的代码效果很好.我的问题涉及将先前提到的内容存储在文本文件中,而不是存储在变量中.从本质上讲,代码将检查print_ids变量中是否存在已看到的tweet.ids列表,以防止每次重新运行程序时LED都只是不断闪烁.我的计划是在计划的作业中运行python代码,但我不想处于每次我重新启动Pi并运行程序的情况下,程序都必须经过我所有的提及并将每次出现的情况写到printing_ids变量. 因此,我的想法是将它们写入文本文件,以使程序在重新启动后仍然可以生存.

So this is my very first attempt at Python and programming the Raspberry Pi. My small project is to light an LED when I get a mention on Twitter. All very simple and the code shown below works well. My question relates to storing the previous mentions in a text file instead of a variable. Essentially the code checks the printed_ids variable for the list of tweet.ids that have already been seen so as to prevent the LED's from just continually flashing every time the program is re-run. My plan is to run the python code in a scheduled job but I don't want to be in a situation where every time I restart the Pi and run the program, the program has to go through all my mentions and write each occurrence to the printed_ids variable. So, my thought was to write them instead to a text file so as the program survives a reboot.

有什么想法/建议吗?

感谢您的帮助.

import sys
import tweepy
import RPi.GPIO as GPIO ## Import GPIO library
import time ## Import 'time' library. Allows use of 'sleep'
GPIO.setmode(GPIO.BOARD) ## Use board pin numbering

CONSUMER_KEY = '******************'

CONSUMER_SECRET = '*****************'

ACCESS_KEY = '**********************'

ACCESS_SECRET = '*********************'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
speed = 2

printed_ids = []

while True:
    for tweet in api.mentions_timeline():
            if tweet.id not in printed_ids:
                    print "@%s: %s" % (tweet.author.screen_name, tweet.text)
                    GPIO.setup(7,GPIO.OUT) ## Setup GPIO Pin 7 to OUT
                    GPIO.output(7,True)## Switch on pin 7
                    time.sleep(speed)## Wait
                    GPIO.output(7,False)## Switch off pin 7
                    f.open('out','w')
                    f.write(tweet.id)
                    ##printed_ids.append(tweet.id)
                    GPIO.cleanup()
                    time.sleep(60)  # Wait for 60 seconds.

推荐答案

您正在寻找的被称为序列化",Python为此提供了许多选项. json模块

What you're looking for is called "serialization" and Python provides many options for that. Perhaps the simplest and the most portable one is the json module

import json

# read:

with open('ids.json', 'r') as fp:
    printed_ids = json.load(fp) 
    # @TODO: handle errors if the file doesn't exist or is empty

# write:

with open('ids.json', 'w') as fp:
    json.dump(printed_ids, fp)

这篇关于Python-将变量写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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