我有以下代码,并希望将推文流写入文本文件。有没有办法将输出包含在同一代码中的文本文件中并将其保存在工作目录中?我是一个IDE爱好者,真的不喜欢使用控制台。我是python的新手(2周),我是R / R Studio用户。
我知道我可以使用:
filename.py > output.txt
我目前正在使用Rodeo,Python 3.6.1。
import oauth2 as oauth
import urllib.request as urllib
api_key = "##"
api_secret = "##"
access_token_key = "##-##"
access_token_secret = "##"
_debug = 0
oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret)
oauth_consumer = oauth.Consumer(key=api_key, secret=api_secret)
signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
http_method = "GET"
http_handler = urllib.HTTPHandler(debuglevel=_debug)
https_handler = urllib.HTTPSHandler(debuglevel=_debug)
'''
Construct, sign, and open a twitter request
using the hard-coded credentials above.
'''
def twitterreq(url, method, parameters):
req = oauth.Request.from_consumer_and_token(oauth_consumer,
token=oauth_token,
http_method=http_method,
http_url=url,
parameters=parameters)
req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token)
headers = req.to_header()
if http_method == "POST":
encoded_post_data = req.to_postdata()
else:
encoded_post_data = None
url = req.to_url()
opener = urllib.OpenerDirector()
opener.add_handler(http_handler)
opener.add_handler(https_handler)
response = opener.open(url, encoded_post_data)
f = open("output.txt", "wb")
def fetchsamples():
url = "https://stream.twitter.com/1.1/statuses/sample.json"
parameters = []
response = twitterreq(url, "GET", parameters)
for line in response:
f.write(line)
if __name__ == '__main__':
fetchsamples()
# f.close()
答案 0 :(得分:0)
除了我之前的评论,我建议查看这个堆栈溢出问题:how to direct output into a txt file in python in windows
引用:
如果你想用Python做,那么你会写:
with open('out.txt', 'w') as f: f.write(something)`
显然,这只是一个微不足道的例子。你明确在
with
区域内做了更多。