PythonAPI流,在一定大小后写入新文件
我有一个python脚本,它维护到Twitter流API的开放连接,并将数据写入json文件。在写入的当前文件达到一定大小后,是否可以在不中断连接的情况下写入新文件?例如,我只传输了一周多的数据,但所有数据都包含在一个文件(~2gb)中,因此解析速度较慢。如果我可以在500mb之后写入一个新文件,那么我将有4个较小的文件(例如dump1.json、dump2.json等)需要解析,而不是一个较大的文件PythonAPI流,在一定大小后写入新文件,python,twitter,twitter-streaming-api,Python,Twitter,Twitter Streaming Api,我有一个python脚本,它维护到Twitter流API的开放连接,并将数据写入json文件。在写入的当前文件达到一定大小后,是否可以在不中断连接的情况下写入新文件?例如,我只传输了一周多的数据,但所有数据都包含在一个文件(~2gb)中,因此解析速度较慢。如果我可以在500mb之后写入一个新文件,那么我将有4个较小的文件(例如dump1.json、dump2.json等)需要解析,而不是一个较大的文件 import tweepy from tweepy import OAuthHandler f
import tweepy
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy.streaming import StreamListener
# Add consumer/access tokens for Twitter API
consumer_key = '-----'
consumer_secret = '-----'
access_token = '-----'
access_secret = '-----'
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
# Define streamlistener class to open a connection to Twitter and begin consuming data
class MyListener(StreamListener):
def on_data(self, data):
try:
with open('G:\xxxx\Raw_tweets.json', 'a') as f:
f.write(data)
return True
except BaseException as e:
print("Error on_data: %s" % str(e))
return True
def on_error(self, status):
print(status)
return True
bounding_box = [-77.2157,38.2036,-76.5215,39.3365]#filtering by location
keyword_list = ['']#filtering by keyword
twitter_stream = Stream(auth, MyListener())
twitter_stream.filter(locations=bounding_box) # Filter Tweets in stream by location bounding box
#twitter_stream.filter(track=keyword_list) # Filter Tweets in stream by keyword
由于每次都要重新打开文件,所以非常简单—在文件名中使用索引,如果文件大小达到阈值,则将其提前
class MyListener(StreamListener):
def __init(self):
self._file_index = 0
def on_data(self, data):
tweets_file = 'G:\xxxx\Raw_tweets{}.json'.format(self._file_index)
while os.path.exists(tweets_file) and os.stat(tweet_file).st_size > 2**10:
self._file_index += 1
tweets_file = 'G:\xxxx\Raw_tweets{}.json'.format(self._file_index)
....
该循环将负责重新启动应用程序,因为您每次都会重新打开文件,这相当简单-在文件名中使用索引,如果文件大小达到阈值,则将其提前
class MyListener(StreamListener):
def __init(self):
self._file_index = 0
def on_data(self, data):
tweets_file = 'G:\xxxx\Raw_tweets{}.json'.format(self._file_index)
while os.path.exists(tweets_file) and os.stat(tweet_file).st_size > 2**10:
self._file_index += 1
tweets_file = 'G:\xxxx\Raw_tweets{}.json'.format(self._file_index)
....
该循环将负责重新启动应用程序Is
os.stat(tweet\u文件).st\u size>2**10
如何设置文件大小?@AndrewR.,这是检查文件大小的方式。我首先检查是否存在以避免异常-您可以使用try…except。您可以将此代码打包到getter方法中-任何适合您的样式都是os.stat(tweet\u file).st\u size>2**10
如何设置文件大小?@AndrewR.,这是检查文件大小的方式。我首先检查是否存在以避免异常-您可以使用try…except。您可以将这段代码打包到getter方法中—任何适合您风格的方法