开发Twitter Bot遇FileNotFoundError:找不到指定文件求助
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

