VSCode中Python读取文件遇FileNotFoundError求助
en-dict.txt in VS Code Python Debugging Hey there, let’s work through why your code can’t find en-dict.txt even though it’s in the same folder as your working file and you’ve set cwd to ${fileDirname} in your launch.json. Here are some actionable steps to fix this:
1. Verify Your Current Working Directory First
Sometimes the cwd setting might not apply as expected. Add a quick check to your code to confirm where Python is looking for the file:
import os print("Current working directory:", os.getcwd())
Run your debug session and check the integrated terminal output. If the printed path isn’t C:\Users\EML\Python Code\Boggle, your launch.json’s cwd configuration isn’t taking effect.
2. Double-Check the File Name and Location
- Make sure the file is exactly named
en-dict.txt—no hidden typos, extra spaces, or capitalization mismatches (Windows is case-insensitive, but small errors likeen_dict.txtinstead ofen-dict.txtcan still cause issues). - Navigate to
C:\Users\EML\Python Code\Bogglein File Explorer and confirm the file is actually there. It’s easy to accidentally save it in the parentPython Codefolder by mistake!
3. Ensure Your Launch.json Configuration is Active
- Restart VS Code to make sure it loads the latest version of your launch.json. Sometimes changes don’t apply until the editor is restarted.
- In the debug panel (Ctrl+Shift+D), confirm you have the
Python: Current Fileconfiguration selected—if there are multiple configurations, you might be using the wrong one.
4. Test with an Absolute Path
To rule out path-related issues, temporarily replace the relative path with an absolute path in your code:
with open(r"C:\Users\EML\Python Code\Boggle\en-dict.txt", "r", encoding="utf8") as file: # Test reading a line to confirm access print(file.readline())
If this works, the problem is definitely with the relative path/working directory. If it still throws an error, check if the file is locked by another program (like Notepad) or if your user account has read permissions for the file (right-click the file → Properties → Security to verify).
5. Check the Integrated Terminal's Initial Path
Sometimes the VS Code integrated terminal might start in a different directory than expected. Open the terminal manually (Ctrl+) and run the cdcommand to see its current path. If it’s notC:\Users\EML\Python Code\Boggle`, adjust the terminal’s default working directory:
- Open VS Code settings (Ctrl+,)
- Search for
terminal.integrated.cwd - Set it to
${fileDirname}to match your debug configuration
内容的提问来源于stack exchange,提问作者MrJoe

