gpt4 book ai didi

python - 更改运行数据流的输出文件?

转载 作者:行者123 更新时间:2023-12-01 03:53:53 25 4
gpt4 key购买 nike

我创建了一个简单的 python 脚本,用于监听过滤后的 Twitter 流并将数据写入一个简单的文本文件。

# -*- coding: utf-8 -*-
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener

# security credentials ommited

searchstr = 'SEARCHSTRING'

class listener(StreamListener):

def on_data(self, data):
with open('data.txt', 'a') as fp:
fp.write(data)
return True

def on_error(self, status):
print(status)
return True

auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)

twitterStream = Stream(auth, listener())
twitterStream.filter(track=[searchstr])

如何每天更改输出文件而不停止数据流?我想以 YYYY-MM-DD-data.txt 格式保存文件。

我的直觉告诉我,我需要另一个 while 循环来连续检查时间并在日期更改后立即打开一个新文件进行输出。你能指出我正确的方向吗?谢谢!

最佳答案

直接替换即可

'data.txt'

time.strftime('%Y-%m-%d',time.localtime())+'-data.txt'  

在使用上述代码之前,不要忘记导入时间

time.localtime() 将获取当前本地时间,使用 time.strftime() 将其格式化为 YYYY-MM-DD。

关于python - 更改运行数据流的输出文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37834792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com