I'm getting 'file not found' running my script. What did I do wrong? Print

  • 26

The error "file not found" usually means your script is trying to access a file that:

  • Doesn't exist at the specified location

  • Has a wrong file path or filename

  • Is located in a different directory than the script expects

 

✅ Common Things to Check:

1. Check the File Path

  • Is the path relative or absolute?

    python
     
    # Relative path (from where you run the script) open("data/input.txt") # Absolute path open("/Users/you/Documents/project/data/input.txt")
  • If you're using a relative path, make sure you’re running the script from the correct working directory.

2. Check the File Name

  • Is the file name spelled exactly right? (File extensions too: .txt, .csv, etc.)

  • File systems like Linux/macOS are case-sensitive:

    • "input.txt" ≠ "Input.txt"

3. Check File Location

  • Is the file in the same folder as your script (for relative paths)?

  • If not, either:

    • Move the file to where the script expects it.

    • Or change the path in your script.

4. Escape Backslashes on Windows

  • If you’re using Windows:

    python
     
    # WRONG open("C:\newfolder\data.txt") # \n and \d are escape characters # RIGHT open("C:\\newfolder\\data.txt") # or open(r"C:\newfolder\data.txt")

5. Check Script’s Working Directory

  • You can print it to debug:

    python
     
    import os print(os.getcwd())
  • That’s the folder your relative paths are based on.


Was this answer helpful?

« Back