[英]How can I read the API authentication data from a file using Python?
I am having trouble with a "Bad Authentication" error when reading my API keys from a file as such: 从文件中读取我的API密钥时,遇到“身份验证错误”错误:
#!/usr/local/bin/python
import tweepy
#open a file called "keys" with keys and tokens for Twitter separated by newlines
keyFile = open('keys', 'r')
consumer_key = keyFile.readline()
consumer_secret = keyFile.readline()
access_token = keyFile.readline()
access_token_secret = keyFile.readline()
keyFile.close()
print "consumer key: " + consumer_key
print "consumer secret: " + consumer_secret
print "access token: " + access_token
print "access token secret: " + access_token_secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
If I manually set my keys, like with consumer_key = "xxx"
, it works fine. 如果我手动设置密钥,例如
consumer_key = "xxx"
,则可以正常工作。 Any tips on why is doesn't work when reading from file? 从文件读取时为何不起作用的任何提示? Thanks.
谢谢。
So it turns out Python was reading the newline characters as well. 因此,事实证明Python也在读取换行符。 The solution was to strip the hidden characters with rstrip():
解决方案是使用rstrip()去除隐藏的字符:
consumer_key = keyFile.readline().rstrip()
keys.txt
file has 4 lines including consumer_key
, consumer_secret
, access_token
and access_token_secret
each separately in a line so we first read all the lines in the keys.txt
file with readlines
method. keys.txt
文件有4行,其中包括consumer_key
, consumer_secret
, access_token
和access_token_secret
分别位于一行中,因此我们首先使用readlines
方法读取keys.txt
文件中的所有行。 We would need to use .rstrip()
in order to remove the unwanted \\n
from end of each string (or other possible unwanted characters). 我们将需要使用
.rstrip()
以便从每个字符串(或其他可能的不需要的字符)的末尾删除不需要的\\n
。 It is a good practice to keep these information in keys.txt
file and add the name of keys.txt
file in .gitignore
when pushing your project to GitHub
so that others won't hack your account when you push your code to GitHub
. 将项目推送到
GitHub
时, keys.txt
将这些信息保留在keys.txt
文件中,并在.gitignore
添加keys.txt
文件的名称,这样,当您将代码推送到GitHub
时,其他人就不会破解您的帐户。
keys_file = open("keys.txt")
lines = keys_file.readlines()
consumer_key = lines[0].rstrip()
consumer_secret = lines[1].rstrip()
access_token = lines[2].rstrip()
access_token_secret = lines[3].rstrip()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.