Urgent.News

What's breaking now, across thousands of outlets.

Tech

FileNotFoundError: [Errno 2] No such file or directory (Fix)

You run your script. Python stops and prints this: FileNotFoundError: [Errno 2] No such file or directory: 'data.txt' But the file is sitting right there in your folder. So what's going on? Below are the six causes behind this error in real programs. Each one has the exact message it gives and a fix. I ran every example on Python 3.11, 3.12 and 3.14 on Windows. All three print the same message.…

When you run your Python script, it may encounter a FileNotFoundError: [Errno 2] No such file or directory. This error occurs when Python tries to open a file, but it can't find the specified file at the given path. Here are six common causes of this error and their respective fixes:

1. You ran Python from a different folder: If you execute your script from a folder that is not the one containing the file, Python will look for the file in the wrong location. To fix this, ensure that you run the script from the same folder as the file or build the path correctly using Python's pathlib module.

2. Typo in the file name: A simple typo in the file name, such as using the wrong spelling or capitalization, can cause this error. Double-check the file name and make sure it matches the actual file name in the folder.

3. Windows hides the real file extension: On Windows, some file types have a default extension appended to the filename. For example, a file named "notes.txt" might be stored as "notes.txt.txt". To resolve this, either rename the file to remove the extra extension or modify the code to use the correct file name, including any additional extensions.

4. Writing to a non-existent folder: When you attempt to write to a file using the 'w' mode, Python creates the file but also creates any missing folders in the path. If the folder does not exist, a FileNotFoundError will occur. To fix this, create the missing folders before writing to the file. You can use the mkdir() method with exist_ok=True or parents=True to create the folder structure.

By understanding these common causes and applying the provided fixes, you can effectively troubleshoot and resolve the FileNotFoundError: [Errno 2] No such file or directory error in your Python programs.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

ValueError: invalid literal for int() with base 10 (Fix)

Your script runs, then Python stops with this: ValueError: invalid literal for int() with base 10: '3.50' You gave int() a string that doesn't look like a whole number.

  • Empty string input triggers ValueError: invalid literal for int() with base 10
  • Decimal numbers with a decimal point cause the ValueError
  • Thousands separators in the input string raise the ValueError

More from Thursday 12 November →