异常后恢复

Recover after exception

如何从异常中恢复并从打开的文件继续行字符串?我卡住了!

    try:
while True:
    with open('us.txt') as f:
        for user in f:
            for tweet in tweepy.Cursor(api.user_timeline, screen_name=user, ).items():
                print(tweet.user.screen_name)
                csvWriter.writerow(tweet.user.screen_name)
except tweepy.TweepError as e:
print(e.reason)
sys.exit()

如果您的(诚然有点令人困惑)问题是询问如何忽略异常,但仍从文件中的位置继续,您应该尝试保持 try:except:块尽可能靠近有问题的行。

例如,如果 csvWriter.writerow(tweet.user.screen_name) 是失败的行,您可以这样做:

while True:
    with open('us.txt') as f:
        for user in f:
            for tweet in tweepy.Cursor(api.user_timeline, screen_name=user,).items():
                print(tweet.user.screen_name)
                try:
                    csvWriter.writerow(tweet.user.screen_name)
                except tweepy.TweepError as e:
                    print(e)

如果错误出现在 for tweet in tweepy.Cursor(... 行,您可以这样做:

while True:
    with open('us.txt') as f:
        for user in f:
            try:
                for tweet in tweepy.Cursor(api.user_timeline, screen_name=user,).items():
                    print(tweet.user.screen_name)
                    csvWriter.writerow(tweet.user.screen_name)
            except tweepy.TweepError as e:
                print(e)

希望对您有所帮助!