First, try to avoid using file
to name your variable, as it's a reserved keyword in Python used for the type file
.
The fixed code:
from twython import Twython, TwythonError
import time
APP_KEY = '##########' # Customer Key here
APP_SECRET = '#############' # Customer secret here
OAUTH_TOKEN = '###############' # Access Token here
OAUTH_TOKEN_SECRET = '################' # Access Token Secret here
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
with open('jokes.txt', 'r+') as fp:
buff = fp.readlines()
for line in buff[:]:
if len(line) < 140:
print("Tweeting...")
twitter.update_status(status=line)
time.sleep(3)
with open('jokes.txt', 'w') as fp:
buff.remove(line)
fp.writelines(buff)
else:
with open('jokes.txt', 'w') as fp:
buff.remove(line)
fp.writelines(buff)
print("Skipped line - Char Length Violation")
continue
except TwythonError as e:
print(e)
Usually - like in this case - it's not a good idea to modify your iterable (list) inside a cycle which iterates on the same iterable. The trick here is the slicing operator in the line for line in buff[:]:
which makes a copy of your buff
list, and iterates on the copy instead of the original buff
list.
Also, when you'd like to overwrite a file, you must open it in 'w' mode, not in 'r+' mode, because 'r+' won't truncate your file first.