You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发Twitter Bot遇FileNotFoundError:找不到指定文件求助

Fixing FileNotFoundError in Your Twitter Bot

Hey there! I spot the issue right away—your read_last_seen function is trying to open a file literally named "FILE_NAME" instead of using the variable you passed in. Let me break this down for you:

The Root Cause

In this line of your read_last_seen function:

file_read = open("FILE_NAME", 'r')

You wrapped FILE_NAME in quotes, which turns it into a string literal. So Python is looking for a file called exactly "FILE_NAME" instead of using the value of your FILE_NAME variable (which is 'last_seen.txt'). That's why it can't find the file even though it's in the same directory!

The Fix

Just remove the quotes around FILE_NAME in the open() call:

def read_last_seen(FILE_NAME):
    file_read = open(FILE_NAME, 'r')  # No quotes here!
    last_seen_id = int(file_read.read().strip())
    file_read.close()
    return last_seen_id

Bonus: Safer File Handling

While we're at it, using Python's with statement is a better practice for file operations—it automatically closes the file even if something goes wrong, so you don't have to remember to call close() manually:

def read_last_seen(FILE_NAME):
    with open(FILE_NAME, 'r') as file_read:
        last_seen_id = int(file_read.read().strip())
    return last_seen_id

def store_last_seen(FILE_NAME, last_seen_id):
    with open(FILE_NAME, 'w') as file_write:
        file_write.write(str(last_seen_id))
    return

One More Tiny Fix

I noticed your final print line is missing a closing parenthesis—this will cause another error once you fix the file issue. Update it to:

print(str(tweet.id) + ' - ' + tweet.full_text)

Give these changes a try, and your bot should be able to find the last_seen.txt file properly!

内容的提问来源于stack exchange,提问作者Hannes Gasteiger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 17:57:45