我正在尝试用Python创建一个机器人来使用tweepy在twitter上管理一些任务。
我在几个文件中保存auth的凭据,但我只想要一个文件。这是一个例子:
for x in range(0, 3):
if x == 0 : from keysaccount1 import keys
if x == 1 : from keysaccount2 import keys
if x == 2 : from keysaccount3 import keys
if x == 3 : from keysaccount4 import keys
CONSUMER_KEY = keys['consumer_key']
CONSUMER_SECRET = keys['consumer_secret']
ACCESS_TOKEN = keys['access_token']
ACCESS_TOKEN_SECRET = keys['access_token_secret']
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True)
存储数据的文件采用此格式,例如keysaccount1:
keys = dict(
consumer_key = 'xxxxxxxxxxxxx',
consumer_secret = 'xxxxxxxxxxxxx',
access_token = 'xxxxxxxxxxxxx',
access_token_secret = 'xxxxxxxxxxxxx',
)
有没有办法将所有这些保存在同一个文件上,因为我在循环中有x变量可用于选择我正在管理的帐户?
答案 0 :(得分:1)
您可以使用单个词典:
auth_data = {
0: {
'consumer_key': 'xxxxxxxxxx',
'consumer_secret': 'xxxxxxxxxxxxx',
'access_token': 'xxxxxxxxxx',
'access_token_secret': 'xxxxxxxxxxxxxx',
}
...
您可以访问以下特定字段:
for x in range(0, 3):
keyset = auth_data[x]
auth = tweepy.OAuthHandler(keyset['consumer_key'], keyset['consumer_secret'])
auth.set_access_token(keyset['access_token'], keyset['access_token_secret'])
api = tweepy.API(auth, wait_on_rate_limit=True)
要保存数据,您只需使用python模块pickle:
import pickle
def read():
with open('data/keys.p', 'r') as f:
return pickle.load(f)
def write(data):
with open('data/keys.p', 'w+') as f:
return pickle.dump(f, data)
# Read data
auth_data = read()
# Write data
write(auth_data)