Ошибка errno 2 no such file or directory

Есть различные способы задать путь к файлу или папке:

  • c:python370script1.py — абсолютный путь

  • script1.py — относительный путь, задается относительно текущей рабочей директории. В данном случае файл должен находиться в текущей директории.

В вашем случае текущая директория C:UsersAcer, вы пытаетесь открыть файл script1.py, но он у вас находится не в этой директории, а в c:python370. Поэтому просто по имени файла вы файл не откроете, нужно указать полный (абсолютный) путь:

exec(open('c:\python370\script1.py').read())

Или запускать Python сразу из нужной директории — двойным кликом по файлу python.exe в папке c:python370 или в окне cmd сначала перейти в директорию, где лежит нужный файл, потом запустить python, и пробовать открыть файл.

В окне cmd:

Microsoft Windows [Version 6.1.7601]
(c) Корпорация Майкрософт (Microsoft Corp.), 2009. Все права защищены.

C:UsersМихаил>

C:UsersМихаил — это текущая директория.

Меняем текущую директорию такой командой (опять же в cmd, до запуска python):

cd c:Python370

В python текущую директорию можно узнать, выполнив команды:

import os
print(os.getcwd())

cwd — сокращение от current working directory — текущая рабочая директория.

Поменять текущую директорию из Python можно так:

import os
os.chdir('c:\python370')

В итоге, если текущая рабочая директория не совпадает с директорией, где лежит файл, то вы не сможете открыть файл просто по его имени. Нужно или указать полный (абсолютный) путь, или изменить текущую директорию.

Кстати, чтобы не экранировать обратные слеши в строке пути, можно использовать «сырые» (raw) строки, с буквой r перед кавычками, например:

import os
os.chdir(r'c:python370')

Most Python developers are facing the issue of FileNotFoundError: [Errno 2] No such file or directory: ‘filename.txt’ in Python when they try to open a file from the disk drive. If you are facing the same problem, then you are in the right spot; keep reading. 🧐

FileNotFoundError: [Errno 2] No Such File or Directory is a common error that occurs in Python when you try to access a file that does not exist in the specified location. This error can be caused by a variety of factors, including incorrect file paths and permissions issues.

In this article, we will discuss, What is the file? How to open it? What is FileNotFoundError? When does the No such file or directory error occur? Reasons for No such file or directory error And how to fix it, so let’s get right into the topic without further delay.

Table of Contents
  1. How to Open a File in Python?
  2. What is the FileNotFoundError in Python?
  3. When Does The “FileNotFoundError: [Errno 2] No Such File or Directory” Error Occur?
  4. Reasons for the “FileNotFoundError: [Errno 2] No Such File or Directory” Error in Python
  5. How to Fix the “FileNotFoundError: [Errno 2] No Such File or Directory” Error in Python?

How to Open a File in Python?

Python provides essential methods necessary to manage files by default. We can do most of the file manipulation using a file object. Before we read or write a file, we have to open it. We use Python’s built-in function open() to open a file. This function creates a file object, which supports many other methods, such as tell, seek, read so on.

Syntax

file object = open(file_name [, access_mode][, buffering])

Access mode and buffering are optional in this syntax, but writing the correct file name is mandatory.

What is the FileNotFoundError in Python?

The FileNotFoundError exception raises during file handling. When you try to access a file or directory which doesn’t exist, it will cause a FileNotFoundError exception.

For example, if we write:

Code

myfile = open ("filename.txt", 'r')

Output

The above code will cause the following error message:

FileNotFoundError [Errno 2] No Such File or Directory

If you want to handle this exception properly, write file-handling statements in the try command. 

Suppose you have a doubt your code may raise an error during execution. If you want to avoid an unexpected ending of the program, then you can catch that error by keeping that part of the code inside a try command.

For example, in this code, we see how to handle FileNotFoundError.

Code

Try:

     #open a file in read mode

    myfile = open ("filename.txt",'r')

    print (myfile.read())

    myfile.close()




# In case FileNotFoundError occurs this block will execute 

except FileNotFoundError:

    print ("File is not exists, skipping the reading process...")

Output

How to Fix FileNotFoundError [Errno 2] No Such File or Directory 1

The compiler executes the code given in the try block, and if the code raises a FileNotFoundError exception, then the code mentioned in the except block will get executed. If there is no error, the “else” block will get executed.

When Does The “FileNotFoundError: [Errno 2] No Such File or Directory” Error Occur?

When we try to access a file or directory that doesn’t exist, we face the error No such file or directory.

Code

myfile=open("filename.txt")

Output

Fix FileNotFoundError [Errno 2] No Such File or Directory

Reasons for the “FileNotFoundError: [Errno 2] No Such File or Directory” Error in Python

Here we see some common reasons for no such file or directory error.

  1. Wrong file name
  2. Wrong extension
  3. Wrong case
  4. Wrong path

The following are a few reasons why this error occurs in Python:

  1. Incorrect file path: One of the most common causes of this error is an incorrect file path. Make sure that you are specifying the correct path to the file you are trying to access. You can use the os.path.exists() function to check if the file exists at the specified location.
  2. File permissions: Another common cause of this error is file permissions. If you do not have permission to access the file, you will get this error. To fix this, you can try changing the file permissions using the chmod command.
  3. File encoding: If you are trying to read a file that has a different encoding than what you are expecting, you may get this error. To fix this, you can use the codecs module to specify the correct encoding when you open the file.
  4. File name case sensitivity: Some operating systems, such as Windows, are not case sensitive when it comes to file names, while others, such as Linux and macOS, are. If you are getting this error on a case-sensitive operating system, it could be because the file name you are specifying does not match the actual file name in the correct case. To fix this, make sure that you are specifying the file name in the correct case.
  5. Check for typos: It’s always a good idea to double-check your file path for typos. Even a small typo can cause this error, so ensure you have typed the file path correctly.
  6. Check for hidden files: Some operating systems hide certain files by default. If you try accessing a hidden file, you may get this error. To fix this, you can try accessing the file by specifying the full path, including the "." at the beginning of the file name, which indicates a hidden file.

As Python programmers, we have to take care of these common mistakes. Always double-check the file’s name, extension, case, and location.

We can write file paths in two ways absolute or relative. 

In Absolute file paths, we tell the complete path from the root to the file name, for example, C:/mydir/myfile.txt. 

In relative file paths, we tell the path from the perspective of our current working directory; for example, if our required file is in the current working directory, we have to write “myfile.txt”.

We can check our current working directory with the help of the following code:

Code

import os

current_working_directory = os.getcwd()

print(current_working_directory)

Output

C:UsersexpertAppDataLocalProgramsPythonPython310

If we want to open a file by just writing its name, we must place it in this directory. Before we move forward to another example of a solution, we have to know about the os built-in module of Python.

The python os module provides several methods that help you perform file-processing operations, such as renaming and deleting files. To utilize this module, you must import it first, and then you can call any related methods.

Now let’s see another example: open a data file and read it.

Code

import os

# store raw string

filepath= r"e:try.txt"

# Check whether a file exists or not

if os.path.exists(filepath)== True:

    print("file exists")

    #open the file and assign it to file object

    fileobj=open(filepath)

    #print data file on screen

    print(fileobj.read())

#else part will be executed if the file doesn't exist

else:

    print("file doesnt exists")

Output

file exists

This is my data file.

Conclusion

In conclusion, FileNotFoundError: [Errno 2] No Such File or Directory is a common error that occurs in Python when you try to access a file that does not exist in the specified location.

This article shows how to fix 🛠️ the “FileNotFoundError: [Errno 2] No Such File or Directory” error in Python. We discuss all the reasons and their solutions.

We also discuss two essential sources that provide a wide range of utility methods to handle and manipulate files and directories on the Windows operating system.

  1. File object methods
  2. OS object methods

Finally, with the help of this article, you get rid of no such file or directory error.

How can we check our current working directory of Python? Kindly share your current working directory path in the comments below 👇.

The error FileNotFoundError: [Errno 2] No such file or directory means that Python can’t find the file or directory you are trying to access.

This error can come from calling the open() function or the os module functions that deal with files and directories.

To fix this error, you need to specify the correct path to an existing file.

Let’s see real-world examples that trigger this error and how to fix them.

Error from open() function

Suppose you use Python to open and read a file named output.txt as follows:

with open('output.txt', 'r') as f:
    data = f.read()

Python will look for the output.txt file in the current directory where the code is executed.

If not found, then Python responds with the following error:

Traceback (most recent call last):
  File ...
    with open('output.txt', 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'output.txt'

If the file exists but in a different directory, then you need to specify the correct path to that file.

Maybe the output.txt file exists in a subdirectory like this:

.
├── logs
│   └── output.txt
└── script.py

To access the file, you need to specify the directory as follows:

with open('logs/output.txt', 'r') as f:
    data = f.read()

This way, Python will look for the output.txt file inside the logs folder.

Sometimes, you might also have a file located in a sibling directory of the script location as follows:

.
├── code
│   └── script.py
└── logs
    └── output.txt

In this case, the script.py file is located inside the code folder, and the output.txt file is located inside the logs folder.

To access output.txt, you need to go up one level from as follows:

with open('../logs/output.txt', 'r') as f:
    data = f.read()

The path ../ tells Python to go up one level from the working directory (where the script is executed)

This way, Python will be able to access the logs directory, which is a sibling of the code directory.

Alternatively, you can also specify the absolute path to the file instead of a relative path.

The absolute path shows the full path to your file from the root directory of your system. It should look something like this:

# Windows absolute path
C:Userssebhastiandocumentslogs

# Mac or Linux
/home/user/sebhastian/documents/logs

Pass the absolute path and the file name as an argument to your open() function:

with open('C:Userssebhastiandocumentslogsoutput.txt', 'r') as f:
    data = f.read()

You can add a try/except statement to let Python create the file when it doesn’t exist.

try:
    with open('output.txt', 'r') as f:
        data = f.read()
except FileNotFoundError:
    print("The file output.txt is not found")
    print("Creating a new file")
    open('output.txt', 'w') as f:
        f.write("Hello World!")

The code above will try to open and read the output.txt file.

When the file is not found, it will create a new file with the same name and write some strings into it.

Also, make sure that the filename or the path is not misspelled or mistyped, as this is a common cause of this error as well.

Error from os.listdir() function

You can also have this error when using a function from the os module that deals with files and directories.

For example, the os.listdir() is used to get a list of all the files and directories in a given directory.

It takes one argument, which is the path of the directory you want to scan:

import os

files = os.listdir("assets")
print(files)

The above code tries to access the assets directory and retrieve the names of all files and directories in that directory.

If the assets directory doesn’t exist, Python responds with an error:

Traceback (most recent call last):
  File ...
    files = os.listdir("assets")
FileNotFoundError: [Errno 2] No such file or directory: 'assets'

The solution for this error is the same. You need to specify the correct path to an existing directory.

If the directory exists on your system but empty, then Python won’t raise this error. It will return an empty list instead.

Also, make sure that your Python interpreter has the necessary permission to open the file. Otherwise, you will see a PermissionError message.

Conclusion

Python shows the FileNotFoundError: [Errno 2] No such file or directory message when it can’t find the file or directory you specified.

To solve this error, make sure you the file exists and the path is correct.

Alternatively, you can also use the try/except block to let Python handle the error without stopping the code execution.

There are several reasons why the FileNotFoundError Errno 2 No such file or directory error can occur:

1. Misspelled filename

There may be times when your filename will have been misspelled. In such a case, the file you specified will not exist in the current directory. So, recheck your filename.

2. Wrong directory

There might be times when your files won’t not exist in the current directory. These are called relative paths and are the most usual occurrence of this error.

To solve the issue, use the following code to check if the file exists in the current directory:

Table of Contents
Hide
  1. Python FileNotFoundError: [Errno 2] No such file or directory
  2. Example FileNotFoundError
  3. Misspelled file name
  4. Invalid file path or directory path
  5. Using a relative path
  6. Solution to FileNotFoundError: [Errno 2] No such file or directory

In Python, when you reference a file, it needs to exist. Otherwise, Python will return a FileNotFoundError: [Errno 2] No such file or directory.

In this tutorial, let’s look at what is FileNotFoundError: [Errno 2] No such file or directory error means and how to solve this in your code.

Python will raise FileNotFoundError when you use the OS library and try to read a file or write a file that does not exist using an open() statement.

It is, of course, excluding you are creating a new file and writing content to the file. Any error message which states FileNotFoundError means that Python cannot find the path of the file you are referencing.

Example FileNotFoundError

The below code will list all the files in a specified folder. We will be using the OS module and os.listdir() method to get a list of files in the specified folder.

import os
for f in os.listdir("/etc"):
	print(f)

Output

Traceback (most recent call last):
  File "Main.py", line 2, in <module>
    for f in os.listdir("/etc/test"):
FileNotFoundError: [Errno 2] No such file or directory: '/etc/test'

Now you can see that Python is throwing FileNotFoundError: [Errno 2] No such file or directory since the folder reference is wrong here.

The possible reasons for this error could be as follows.

Misspelled file name

The error will often occur due to misspelled filenames, so providing the correct file name would solve the issue.

Invalid file path or directory path

Sometimes you might give a wrong file path or directory path which does not exist. It usually happens even with the network path when it’s unreachable. So ensure that the file path is correct and if you are placing the file in the network path, make sure it’s reachable and accessible.

Using a relative path

If you use a relative path, the file would be searched in the current working directory and not in the original path. So ensure you give an absolute path of the file to resolve the error.

Solution to FileNotFoundError: [Errno 2] No such file or directory

We will correct our above code by referencing the proper directory where the file exists. This time, we will also use an absolute path instead of a relative path to ensure it’s referencing the correct directory.

import os
for f in os.listdir("C:/Projects/Tryouts/etc"):
	print(f)

Output

python.txt
index.md
Python Data Science Ebook.pdf

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Возможно, вам также будет интересно:

  • Ошибка errno 111 connection refused
  • Ошибка errcan что может быть
  • Ошибка errcan на приоре что это
  • Ошибка err7 на 3d принтере
  • Ошибка err network changed как исправить

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии