如何使用Python从文件中读取API身份验证数据?

如何使用Python从文件中读取API身份验证数据?,python,twitter-oauth,tweepy,Python,Twitter Oauth,Tweepy,从文件读取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(

从文件读取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)

如果我手动设置我的钥匙,如使用
consumer\u key=“xxx”
,它可以正常工作。关于从文件读取时为什么is不起作用的提示?谢谢。

因此,Python也在读取换行符。解决方案是使用rstrip()去除隐藏字符:


consumer\u key=keyFile.readline().rstrip()

因此,Python也在读取换行符。解决方案是使用rstrip()去除隐藏字符:


consumer\u key=keyFile.readline().rstrip()
keys.txt
文件有4行,包括
consumer\u key
consumer\u secret
access\u token
access\u token\u secret
分别在一行中,因此我们首先使用
readlines
方法读取
keys.txt
文件中的所有行。我们需要使用
.rstrip()
,以便从每个字符串的末尾(或其他可能不需要的字符)删除不需要的
\n
。将项目推送到
GitHub
时,最好将这些信息保存在
keys.txt
文件中,并将
keys.txt
文件名添加到
.gitignore
中,这样别人就不会在您将代码推到
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()

keys.txt
文件有4行,其中包括
consumer\u key
consumer\u secret
access\u token
access\u token\u secret
分别排成一行,因此我们首先使用
readlines
方法读取
keys.txt文件中的所有行。我们需要使用
.rstrip()
,以便从每个字符串的末尾(或其他可能不需要的字符)删除不需要的
\n
。将项目推送到
GitHub
时,最好将这些信息保存在
keys.txt
文件中,并将
keys.txt
文件名添加到
.gitignore
中,这样别人就不会在您将代码推到
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()

最好是添加一些说明,而不仅仅是代码片段,以便更好地理解。最好是添加一些说明,而不仅仅是代码片段,以便更好地理解。是的,我也有同样的问题。我尝试了
consumer\u key=f.readline()[:-1]
,但没有奏效。谢谢是的,我也有同样的问题。我尝试了
consumer\u key=f.readline()[:-1]
,但没有奏效。谢谢