Ошибка no such file found

Ошибка «No such file or directory» появляется, когда нужный файл отсутствует.

Давайте исключим самое банальное:

1. Файла нет на диске

user@pc1:~$ cat hello.cpp
cat: hello.cpp: No such file or directory

Поскольку отсутствует файл hello.cpp , то выводится ошибка

2. Кириллица в названии

Проверьте, что в названии файла буква «с» не написана кириллицей. Например в расширении «.cpp».

3. Неправильный путь

Пример из Python

data_file= open ("../text.txt",'r')

«../» в общем случае говорит о том, что файл будет искаться на 1 директорию выше, чем файл с кодом.

Если файл лежит в директории с кодом, то следует писать:

data_file= open ("./text.txt",'r')

4. Неправильная битность

Вы можете увидеть ту же ошибку, если пытаетесь запустить например 64-битное приложение на 32-битной Windows

5. Более экзотические причины.

Причина ошибки может быть самой разной, в зависимости от приложения, которое вы используете.

Если это как раз тот случай, напишите о нем в комментариях, в будущем это очень поможет другим.

Нашли опечатку или ошибку? Выделите её и нажмите Ctrl+Enter

Помогла ли Вам эта статья?

Understanding absolute and relative paths

The term path means exactly what it sounds like. It shows the steps that need to be taken, into and out of folders, to find a file. Each step on the path is either a folder name, the special name . (which means the current folder), or the special name .. (which means to go back/out into the parent folder).

The terms absolute and relative also have their usual English meaning. A relative path shows where something is relative to some start point; an absolute path is a location starting from the top.

Paths that start with a path separator, or a drive letter followed by a path separator (like C:/foo) on Windows, are absolute. (On Windows there are also UNC paths, which are necessarily absolute. Most people will never have to worry about these.)

Paths that directly start with a file or folder name, or a drive letter followed directly by the file or folder name (like C:foo) on Windows, are relative.

Understanding the «current working directory»

Relative paths are «relative to» the so-called current working directory (hereafter abbreviated CWD). At the command line, Linux and Mac use a common CWD across all drives. (The entire file system has a common «root», and may include multiple physical storage devices.) Windows is a bit different: it remembers the most recent CWD for each drive, and has separate functionality to switch between drives, restoring those old CWD values.

Each process (this includes terminal/command windows) has its own CWD. When a program is started from the command line, it will get the CWD that the terminal/command process was using. When a program is started from a GUI (by double-clicking a script, or dragging something onto the script, or dragging the script onto a Python executable) or by using an IDE, the CWD might be any number of things depending on the details.

Importantly, the CWD is not necessarily where the script is located.

The script’s CWD can be checked using os.getcwd, and modified using os.chdir. Each IDE has its own rules that control the initial CWD; check the documentation for details.

To set the CWD to the folder that contains the current script, determine that path and then set it:

os.chdir(os.path.dirname(os.path.abspath(__file__)))

Verifying the actual file name and path

  • There are many reasons why the path to a file might not match expectations. For example, sometimes people expect C:/foo.txt on Windows to mean «the file named foo.txt on the desktop». This is wrong. That file is actually — normally — at C:/Users/name/Desktop/foo.txt (replacing name with the current user’s username). It could instead be elsewhere, if Windows is configured to put it elsewhere. To find the path to the desktop in a portable way, see How to get Desktop location?.

    It’s also common to mis-count ..s in a relative path, or inappropriately repeat a folder name in a path. Take special care when constructing a path programmatically. Finally, keep in mind that .. will have no effect while already in a root directory (/ on Linux or Mac, or a drive root on Windows).

    Take even more special care when constructing a path based on user input. If the input is not sanitized, bad things could happen (e.g. allowing the user to unzip a file into a folder where it will overwrite something important, or where the user ought not be allowed to write files).

  • Another common gotcha is that the special ~ shortcut for the current user’s home directory does not work in an absolute path specified in a Python program. That part of the path must be explicitly converted to the actual path, using os.path.expanduser. See Why am I forced to os.path.expanduser in python? and os.makedirs doesn’t understand «~» in my path.

  • Keep in mind that os.listdir will give only the file names, not paths. Trying to iterate over a directory listed this way will only work if that directory is the current working directory.

  • It’s also important to make sure of the actual file name. Windows has an option to hide file name extensions in the GUI. If you see foo.txt in a window, it could be that the file’s actual name is foo.txt.txt, or something else. You can disable this option in your settings. You can also verify the file name using the command line; dir will tell you the truth about what is in the folder. (The Linux/Mac equivalent is ls, of course; but the problem should not arise there in the first place.)

  • Backslashes in ordinary strings are escape sequences. This causes problems when trying to a backslash as the path separator on Windows. However, using backslashes for this is not necessary, and generally not advisable. See Windows path in Python.

  • When trying to create a new file using a file mode like w, the path to the new file still needs to exist — i.e., all the intervening folders. See for example Trying to use open(filename, ‘w’ ) gives IOError: [Errno 2] No such file or directory if directory doesn’t exist. Also keep in mind that the new file name has to be valid. In particular, it will not work to try to insert a date in MM/DD/YYYY format into the file name, because the /s will be treated as path separators.

Автор Сообщение
 

СообщениеДобавлено: 03.06.2012 14:02 

[профиль]

Member

Статус: Не в сети
Регистрация: 02.11.2010

После установки дров на мать начало выскакивать окошко no such file found
#77
как убрать)
папки темп, автазагрузка и папка чипсет чекнуты.


_________________
«Обдумай причины, побуждающие тебя поступать так, как ты намереваешься поступить; взвесь все обстоятельства своего дела…

Последний раз редактировалось CEH9I 03.06.2012 14:10, всего редактировалось 1 раз.

Реклама

Партнер
 
ZSaimont

Member

Статус: Не в сети
Регистрация: 17.04.2008
Откуда: Москва

CEH9I а если создать его?


_________________
GA-P55-US3L; i5-750 + Performa @ 3.8Ghz; GTX780; 2xKVR1333D3N9K2/4G

 
CEH9I

Member

Статус: Не в сети
Регистрация: 02.11.2010

На сколько я понимаю то где то в реестре висит запись на автозагрузку этой фигни.

Цитата:

CEH9I а если создать его?

Мне не чего не даст.


_________________
«Обдумай причины, побуждающие тебя поступать так, как ты намереваешься поступить; взвесь все обстоятельства своего дела…

 
ageich

Member

Статус: Не в сети
Регистрация: 23.10.2009
Откуда: Алтайский край
Фото: 0

поиск по реестру C:WindowsChipsetAsusSetup.ini и удалить эту запись

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 7

Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете добавлять вложения

Лаборатория

Новости

In Python, the files play a crucial rule while reading or writing the data in bulk. To do so, various methods, such as open(), write(), readline(), etc., are used. However, sometimes while accessing the file, the error “No such file or directory” is invoked in Python. To fix this error, different solutions are provided in this article in detail.

This write-up will provide the causes and solutions of the error “no such file or directory” in Python using the following terms:

  • Reason 1: File Does Not Exist
  • Solution 1: Move the File to Python Working Directory
  • Solution 2: Provide Correct Absolute Path of File
  • Reason 2: Incorrect File Name
  • Solution: Use the Correct File Name

Reason 1: File Does Not Exist

The “FileNotFoundError: [Errno 2] No such file or directory” appears in Python when a user tries to access a file that does not exist in the particular location, as shown below:

From the above snippet, it is verified that the program throws an error when we try to access a file that is not present in the directory.

Solution 1: Move the File to Python Working Directory

To fix this error, the file must be moved to a current working directory of Python, or the absolute path of the file must be written correctly.

File Location:

The file we want to access is currently placed in the current working directory of Python. The below snippet shows you the name and location of the file:

If you don’t know the current working directory of Python, you can use the given below code to get the current working directory:

Code:

import os

current_directory = os.getcwd()

print(current_directory)

In the above code, the “os.getcwd()” function of the standard “os” module is used to get the current working directory of Python.

Output:

The above output shows the present working directory of Python.

Now, after knowing the location of the file, we just simply type the name along with the format (.txt) to access the file in the Python program. An example code of this is shown below:

Code:

file = open("sample.txt", "r")

print(file.read())

In the above code, the “open()” function accepts the name of the file and mode of the file as an argument.

Output:

The above output shows that the program successfully read the file.

Solution 2: Provide Correct Absolute Path of File

Another way to solve the “no such file or directory” error in Python is by providing an absolute path inside the function.

File Location:

The path of the file placed at another location is shown below in the snippet:

Now, the above file is accessed using the “open()” function in the given below code example:

Code:

file = open("F:itslinuxfosssample.txt", "r")

print(file.read())

In the above code, the absolute path along with the file name is placed inside the parentheses of “open()” function as a first argument. The mode “r” indicates that the file is accessed for reading purposes and is placed as the second argument.

Output:

The above output verified that the file had been successfully read using the specified location.

Reason 2: Incorrect File Name

The error also occurs due to incorrect file or path names as shown in the following snippet:

The above snippet shows that the program throws an error when the file name is misspelled.

Solution: Use the Correct File Name

To fix this error, correct the file name and always make sure to check the spelling of the file and the path location of the file carefully.

Code:

file = open("F:itslinuxfosssample.txt", "r")

print(file.read())

In the above code, the file name is corrected and verified.

Output:

The above output verified that the file had been read successfully.

That’s it from this tutorial!

Conclusion

The “FileNotFoundError: [Errno 2] No such file or directory” error occurs when the user tries to access the file that does not exist at the specified location or at the current working directory of Python. To solve this error, move the file to the working directory of Python or provide a correct absolute path name. Several reasons and solutions for the error “No such file or directory” in Python are addressed in this article.

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.

Понравилась статья? Поделить с друзьями:
  • Ошибка no such device ostree
  • Ошибка no such device grub
  • Ошибка no start signal detected forcing start
  • Ошибка no space left on device на android
  • Ошибка no sound card detected