我正在尝试获取不同日期的推文,并将它们附加到数据帧中,最后写入csv文件。文本文件附加推文但df被覆盖,csv文件也被覆盖。
import datetime
x= datetime.date.today()
y= x.strftime('%Y-%m-%d')
c= datetime.date.today() - datetime.timedelta(days=1)
d= c.strftime('%Y-%m-%d')
e= datetime.date.today() - datetime.timedelta(days=2)
f= e.strftime('%Y-%m-%d')
g= datetime.date.today() - datetime.timedelta(days=3)
h= g.strftime('%Y-%m-%d')
i= datetime.date.today() - datetime.timedelta(days=4)
j= i.strftime('%Y-%m-%d')
k= datetime.date.today() - datetime.timedelta(days=5)
l= k.strftime('%Y-%m-%d')
m= datetime.date.today() - datetime.timedelta(days=6)
n= m.strftime('%Y-%m-%d')
o= datetime.date.today() - datetime.timedelta(days=7)
p= o.strftime('%Y-%m-%d')
a=[p,n,l,j,h,f,d]
b=[n,l,j,h,f,d,y]
for i in range(len(a)):
data = Cursor(api.search, q, since=a[i], until=b[i]).items()
tweet_data = []
# current_working_dir = os.path.dirname(os.path.realpath(__file__))
current_working_dir = "./"
log_tweets = current_working_dir + '_tweets.txt'
with open(log_tweets, 'a') as outfile:
for tweet in data:
tweet_data.append(json.loads(json.dumps(tweet._json)))
outfile.write(json.dumps(tweet._json))
outfile.write("\n")
print "text file written"
# Create the dataframe to be used
tweets = pd.DataFrame()
tweets['Tweet'] = map(lambda tweet: tweet['text'].encode('utf-8'), tweet_data)
tweets['Dates'] = map(lambda tweet: time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y')), tweet_data)
tweets['User'] = map(lambda tweet: tweet['user']['screen_name'], tweet_data)
tweets.to_csv("string.csv", sep=",", index=False)
print " String CSV written......"
我的CSV文件正在为每个连续日期覆盖。我试图附加数据帧但失败了。
答案 0 :(得分:1)
Pandas to_csv的默认模式是write,它将覆盖该文件。追加的正确方法是:
tweets.to_csv('string.csv', mode='a', header=False, index=False)
同时将标题设置为False,以便不再添加