Python Script to backup tweets

1 minute read

It was some conversations in Twitter with @aashiks and @geohacker that made me write this script. The conversation goes like this:

geohacker : What is the best way to archive my twitter timeline?
            I think I'm loosing several precious tweets! #help #please
ershus    : Copy-paste ? ;)
aashiks   : @geohacker ask @ershus to write a python script and
            retrieve data using the twitter api
ershus    : @aashiks My god! ഞാന്‍ ഒന്നും പറഞ്ഞില്ല ! ദയവായ് ക്ഷമിക്കൂ.....
            PS: വിടാന്‍ ഉദ്ദേശമില്ല, ശ്രമിക്കാം :) ( @geohacker )
aashiks   : @geohacker - kandallo ? thats how you do it :D
            @ershus vegam V0.1 erakku :D

Well, this little script is born! Thanks to them, else I would not have written anything like this.

This is my first 'working' python script and I'm very happy to share with you. I've just started using python,  you may be able to suggest a lot of improvements in the code. Please help me by pointing out the mistakes and other suggestions.

This script uses python-twitter library,  please make sure it's installed before running the code.

Thanks to Rajeesh ettan who helped me with unicode issues and time.sleep() :)

Here's the code:

#! /usr/bin/env python
# -*- coding: utf-8 -*-

# Version 1.0
# Copyright (C) 2010 - Ershad K
# Licensed under GPL Version 3

import os, sys, codecs
import time
import twitter

# Change the following values
username = 'USERNAME'
password = 'PASSWORD'
backup_file = 'twitterbackfile' #File name or Path + File name
sleep_time = 5 #seconds

fout =, 'a') #to create such a file
api = twitter.Api(username, password)

while (True):
	timeline = api.GetFriendsTimeline(username)
	for s in timeline:
		#print "%st%s" % (, s.text)
		tweet = + "t" + s.text
		fin = open(backup_file, 'r')
		x =
		y = x.find(tweet.encode("utf-8"))

		if y < 0:
			fout =, 'a')
			text = + "t" + s.text + "n"

Thank you :)

Leave a Comment

Your email address will not be published. Required fields are marked *