Editor

FileNotFoundError: [Errno 2] No such file or directory

What it means

Python could not find a file at the path you gave. A name without folders, like 'data.txt', is looked up only in the current working folder. The file may not exist yet, its name may differ slightly, or a folder in the path may be missing.

1. Reading a file that has not been created yet

This raises the error

Broken
with open('data.txt') as f:
print(f.read())
Output
Traceback (most recent call last):
  File "<exec>", line 1, in <module>
FileNotFoundError: [Errno 44] No such file or directory: 'data.txt'

The fix

Fixed
with open('data.txt', 'w') as f: # 'w' creates the file
f.write('first line\n')
with open('data.txt') as f:
print(f.read())
Output
first line

Opening with 'r', the default, only reads files that already exist. Mode 'w' creates the file (or empties it), and 'a' creates it or adds to the end.

Try fixing it yourself in the editor

2. Not checking that the file exists

This raises the error

Broken
with open('settings.txt') as f:
theme = f.read().strip()
print('Theme:', theme)
Output
Traceback (most recent call last):
  File "<exec>", line 1, in <module>
FileNotFoundError: [Errno 44] No such file or directory: 'settings.txt'

The fix

Fixed
import os
if os.path.exists('settings.txt'):
with open('settings.txt') as f:
theme = f.read().strip()
else:
theme = 'dark' # a default when there is no file yet
print('Theme:', theme)
Output
Theme: dark

os.path.exists() lets the program fall back to a default when the file is missing. Catching FileNotFoundError with try / except does the same job.

Try fixing it yourself in the editor

3. Writing into a folder that does not exist

This raises the error

Broken
with open('reports/summary.txt', 'w') as f:
f.write('All good')
print('Saved')
Output
Traceback (most recent call last):
  File "<exec>", line 1, in <module>
FileNotFoundError: [Errno 44] No such file or directory: 'reports/summary.txt'

The fix

Fixed
import os
os.makedirs('reports', exist_ok=True) # create the folder first
with open('reports/summary.txt', 'w') as f:
f.write('All good')
print('Saved:', os.path.exists('reports/summary.txt'))
Output
Saved: True

Mode 'w' creates a missing file but never a missing folder. os.makedirs(..., exist_ok=True) creates the folders, and does nothing if they are already there.

Try fixing it yourself in the editor

When you see this error, check

  • Print os.getcwd() and os.listdir() to see which folder Python is in and what is there.
  • Check the exact file name, including the extension: data.txt and data.txt.txt are different files.
  • In the pythoncompiler.io editor, upload a data file from the Files panel first. Your code can then open it by its name.
  • On Windows, use forward slashes in paths, or a raw string like r'C:\files\data.txt'.

All Python errors · How to read a traceback · Step through your code