Python - writing a variable to a text file

夙愿已清 提交于 2019-12-24 10:45:37

问题


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.

Any thoughts/recommendations?

Thanks for your help.

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.

回答1:


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)


来源:https://stackoverflow.com/questions/19294745/python-writing-a-variable-to-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!