What does [Errno 2] mean in python?

Question:

I was playing around with python, and I was trying to open a file. I accidentally made a typo, and got the expected error:

FileNotFoundError: [Errno 2] No such file or directory: ‘tlesting.py’

It was supposed to be testing.py if you are wondering.

Of course, I expected the error, but I want to know the reason behind why [Errno 2] is included. I got curious, so I tried raising the error myself: raise FileNotFoundError("This is a test"), and got an output of: FileNotFoundError: This is a test, but no [Errno 2] anymore. Is this something to do with the current version of python or my current operating system?

Asked By: 5rod

||

Answers:

Common reason to this error is like the text says- file not found. mostly this will be because you try to access a filename without the path.

example:

import os

for root, dirs, files in os.walk('C:/Windows/System32/drivers'):
    for file in files:
        with open("hosts", "r") as file1:
            read_content = file1.read()
            print(read_content)

I get [Errno 2] No such file or directory: ‘hosts’. This is because the filename exists in C:WindowsSystem32driversetchosts, and the variable file1 contains only the value ‘hosts’. In this example I need to join the current path to the filename….

Answered By: Eitan

To add the [Errno 2] tag, you can pass the appropriate error number as an explicit first argument:

>>> import errno
>>> raise FileNotFoundError("foo")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: foo
>>> raise FileNotFoundError(errno.ENOENT, "foo")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] foo
Answered By: chepner
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.