制作文本冒险游戏遇FileNotFoundError,且无法使用绝对路径的解决方法
Hey there! Let's sort out that frustrating FileNotFoundError you're hitting when running your text adventure game. Here's what's going on and how to fix it—no absolute paths required:
Why You're Seeing This Error
Python looks for files in its current working directory by default. If your story file (the one you're trying to open with file = open("Prison Break B...")) isn't in that exact directory, or there's a typo in the filename, Python can't locate it.
Step-by-Step Fixes
1. Keep Your Script and File in the Same Folder
Move your Python script (e.g., prison_break.py) and your story text file into the exact same folder. This is the simplest way to make Python find the file without needing any path at all.
2. Double-Check Filename Spelling & Case
- Make sure the filename in your
open()call matches the actual file exactly—including spaces, capitalization, and file extensions (like.txt).- For example: If your file is named
Prison_Break_Backstory.txt, your code should useopen("Prison_Break_Backstory.txt"), not a truncated or misspelled version like"Prison Break B...".
- For example: If your file is named
- Note: Mac and Linux are case-sensitive, so
prison.txtis different fromPrison.txt. Windows is less strict, but it's best to match exactly anyway.
3. Unhide File Extensions (Windows Users)
Windows sometimes hides file extensions by default. If you think your file is named Prison Break Backstory but it's actually Prison Break Backstory.txt (with the .txt hidden), Python won't find it. To fix this:
- Open File Explorer → Go to View tab → Check the "File name extensions" box.
- Now you can see the full filename, and update your code to match it.
4. Verify Your Working Directory (Optional)
If you're still unsure where Python is looking for files, add this code at the top of your script to print the current working directory:
import os print("Current working directory:", os.getcwd())
Run the script, and move your story file into the path that gets printed.
Quick Code Fix: Your Start Condition
While we're at it, there's a small bug in your start choice check:
# Your original code (buggy) if choice == 'S'or's' :
This will always evaluate to True because 's' is a non-empty string (which counts as True in Python). Instead, use one of these:
# Option 1: Check both cases explicitly if choice == 'S' or choice == 's': # Option 2: Convert input to uppercase first if choice.upper() == 'S': # Option 3: Check against a list of valid inputs if choice in ['S', 's']:
内容的提问来源于stack exchange,提问作者Pr Music

