<p>首先,尽量避免使用<code>file</code>来命名变量,因为它是Python中用于类型<code>file</code>的保留关键字。你知道吗</p>
<p>固定代码:</p>
<pre><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)
</code></pre>
<p>通常-就像在本例中-在循环内修改iterable(列表)不是一个好主意,循环对同一iterable进行迭代。这里的技巧是第<code>for line in buff[:]:</code>行中的切片操作符,它生成<code>buff</code>列表的副本,并在副本上而不是在原始的<code>buff</code>列表上迭代。你知道吗</p>
<p>另外,如果要覆盖文件,必须以“w”模式打开,而不是以“r+”模式打开,因为“r+”不会首先截断文件。你知道吗</p>