Есть различные способы задать путь к файлу или папке:
-
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')
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.
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
- How to Open a File in Python?
- What is the FileNotFoundError in Python?
- When Does The “FileNotFoundError: [Errno 2] No Such File or Directory” Error Occur?
- Reasons for the “FileNotFoundError: [Errno 2] No Such File or Directory” Error in Python
- 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:
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
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
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.
- Wrong file name
- Wrong extension
- Wrong case
- Wrong path
The following are a few reasons why this error occurs in Python:
- 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. - 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. - 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. - 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.
- 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.
- 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.
- File object methods
- 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 👇.
0 / 0 / 0 Регистрация: 04.11.2014 Сообщений: 1 |
|
1 |
|
04.11.2014, 21:44. Показов 157379. Ответов 18
Помогите, пожалуйста.
0 |
2740 / 2339 / 620 Регистрация: 19.03.2012 Сообщений: 8,830 |
|
04.11.2014, 22:41 |
2 |
В какой папке лежит файл и как вы запускаете интерпретатор?
0 |
Andrej И целого heap’а мало 95 / 56 / 17 Регистрация: 31.07.2014 Сообщений: 291 |
||||
05.11.2014, 19:17 |
3 |
|||
Yankin943,
что напечатает?
0 |
alex925 2740 / 2339 / 620 Регистрация: 19.03.2012 Сообщений: 8,830 |
||||
05.11.2014, 20:24 |
4 |
|||
Или лучше вот так:
0 |
0 / 0 / 0 Регистрация: 29.05.2015 Сообщений: 2 |
|
29.05.2015, 12:34 |
5 |
Код Python Мне пишет: Python 3.4.3 лежит в папке C:Python34, файл который пытаюсь запустить в C:UsersSanchezDocumentsPython называется script1.py (расширение правильное) Не понимаю что не так. В IDLE всё запускается. Двойным нажатием на сам файл script1.py дапускается командная строка и выполняется сама операция в файле (правда пришлось в конце операции написать : input(), что бы коммандная строка сраже после выполнения операции не закрывалась.
0 |
0 / 0 / 0 Регистрация: 16.04.2015 Сообщений: 29 |
|
29.05.2015, 14:04 |
6 |
SanchezELgringo, Этот код нужно не в cmd копировать, а в питоновский файл и запускать
0 |
t1m0n 637 / 415 / 27 Регистрация: 03.11.2009 Сообщений: 1,855 |
||||
31.05.2015, 18:49 |
7 |
|||
Решениефайл который вы пытаетесь открыть должен лежать либо в рядом с файлом скрипта, либо в скрипте указывать путь к файлу
0 |
0 / 0 / 0 Регистрация: 13.01.2015 Сообщений: 28 |
|
12.05.2016, 17:40 |
8 |
Добрый день .Ребят помогите пожалуйста. при установке всё гладко идёт wifiphisher на линуксе только вот при команде python wifiphisher. py выходит такая ошибка python can’t open file wifiphisher py error 2 no such file directory
0 |
2740 / 2339 / 620 Регистрация: 19.03.2012 Сообщений: 8,830 |
|
12.05.2016, 22:51 |
9 |
Значит такого файла нет в текущей директории.
0 |
0 / 0 / 0 Регистрация: 13.01.2015 Сообщений: 28 |
|
12.05.2016, 23:41 |
10 |
Да нашёл всё и остальное по порядку .только очень долго приходится ждать.Пока что не получил пароль .и страница тоже почему то не открывается
0 |
0 / 0 / 0 Регистрация: 13.01.2015 Сообщений: 28 |
|
12.05.2016, 23:45 |
11 |
Только поиск в терминале Миниатюры
0 |
alex925 2740 / 2339 / 620 Регистрация: 19.03.2012 Сообщений: 8,830 |
||||
12.05.2016, 23:47 |
12 |
|||
И к чему это ты скинул? Тут нет ничего, что относится к вопросу. Тебе надо в рабочей папке проверить наличие вызываемого скрипта и все.
0 |
0 / 0 / 0 Регистрация: 13.01.2015 Сообщений: 28 |
|
12.05.2016, 23:51 |
13 |
На сайте другая инструкция и я поэтому в терминале жду пароля.Там по фото показывают.Но почему то долго и очень долго приходится ждать.Та ссылка на фото у меня не открывается а на сайте написано что должно открываться.а ключа в другом месте надо искать?
0 |
2740 / 2339 / 620 Регистрация: 19.03.2012 Сообщений: 8,830 |
|
12.05.2016, 23:57 |
14 |
Ты не заметил, что ты отклонился от темы, причем совсем и не рассказал ничего о проблеме. Сначала у тебя были проблемы с запуском скрипта, а сейчас ты говоришь, что не можешь к хостинку подключиться. Это вообще не по теме данной ветки.
0 |
0 / 0 / 0 Регистрация: 13.01.2015 Сообщений: 28 |
|
13.05.2016, 00:02 |
15 |
Проблема было в расположение файла.скинул всё на рабочий стол и оттуда указывал путь к файлу Добавлено через 3 минуты Для начала, запустите Kali и откройте терминал. Затем скачайте Wifiphisher с GitHub и распакуйте код. kali > tar -xvzf /root/wifiphisher-1.1.tar.gz. и с этим всё пошло лучше. Wifiphisher.py тут есть.а проблема с этим было
0 |
2740 / 2339 / 620 Регистрация: 19.03.2012 Сообщений: 8,830 |
|
13.05.2016, 00:03 |
16 |
Проверь какие файлы есть в текущей папке (папка из которой ты запускаешь скрипт) с помощью ls, судя по всему там нет твоего скрипта. После этого поговорим уже.
0 |
0 / 0 / 0 Регистрация: 13.01.2015 Сообщений: 28 |
|
13.05.2016, 00:10 |
17 |
не было Wifiphisher.py.tar -xvzf /root/wifiphisher-1.1.tar.gz .а на этом есть.на терминале когда распаковал так сразу заметил.и в папке было этот файл.но по этой ссылке git clone https://github/sophron/wifiphisher загруженного архива не было Wifiphisher.py. Добавлено через 3 минуты
0 |
2740 / 2339 / 620 Регистрация: 19.03.2012 Сообщений: 8,830 |
|
13.05.2016, 00:24 |
18 |
Я вот честно не понимаю тебя. Ты сам говоришь, что в нужном тебе месте нет файла, который ты пытаешься запустить, но все равно, что-то хочешь, о чем можно вообще вести в этой ситуации разговор?
0 |
20 / 9 / 0 Регистрация: 16.01.2019 Сообщений: 288 |
|
26.01.2019, 22:17 |
19 |
ну и тема((( думал найду ответ по указанной в начале проблеме, а тут какой то невнятный перебор начался… то ему файл открыть, то в линуксе что то запустить(((
1 |
FileNotFoundError: [Errno 2] No such file or directory is an error that occurs when a Python program or script attempts to access a specific file but does not find the specified file in the designated location.
This generally indicates either that the path to the file is incorrect, or that the user does not have sufficient permissions to access it.
In this article, we will discuss 3 ways to fix this issue.
Check the spelling and case of the file or directory name
Make sure that you are spelling the file or directory name correctly and that you are using the correct case. There may be times when your filename will have been misspelled.
If you accidentally use escape sequences in a file path in Python, it can cause problems when trying to access the file.
For example, consider the following code:
with open('C:pathtonickfilename.ext', 'r') as f:
# Do something with the file
contents = f.read()
print(contents)
This code is intended to open the file filename.ext located at the path C:pathtonickfilename.ext.
However, the escape sequences n are interpreted as a line break character. This may not be the intended path, and could cause the file to not be found.
To avoid this problem, you can use a raw string literal to specify the file path. A raw string literal is a string that is prefixed with the r character, which tells Python to interpret the string literally, without interpreting any escape sequences.
For example:
with open(r'C:pathtonickfilename.ext', 'r') as f:
# Do something with the file
contents = f.read()
print(contents)
This code will open the file filename.ext located at the path C:pathtonickfilename.ext, without interpreting the backslashes as escape sequences.
Check the path to the file or directory
Make sure that you are using the correct path to the file or directory.
It’s a common misconception that relative path is relative to the location of the python script, but this is not true. Relative file paths are always relative to the current working directory, and the current working directory doesn’t have to be the location of your python script .
You can use the ls command to list the contents of the directories along the path to the file or directory.
Using an absolute path to open a file in Python can be useful if you want to ensure that the file is always accessed from the same location, regardless of the current working directory.
file = open(r'C:pathtoyourfilename.ext') //absolute path
This code will open the file filename.ext located at the absolute path C:pathtoyourfilename.ext.
Change the current working directory before opening the file
You can use the os.chdir() function to change the current working directory before opening a file in Python.
For example:
import os
# Change the current working directory to 'C:pathtoyourdirectory'
os.chdir(r'C:pathtoyourdirectory')
# Open the file 'filename.ext' in the current working directory
with open('filename.ext', 'r') as f:
# Do something with the file
contents = f.read()
print(contents)
This code will change the current working directory to C:pathtoyourdirectory, and then open the file filename.ext located in this directory.
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:
Expected behaviour
Run a program that reads a file stored in the same directory as the program.
Actual behaviour
VS Code is returning the following in the terminal:
Traceback (most recent call last):
File "/Filepath/10-1_learning_python.py", line 3, in <module>
with open(filename) as file_content:
FileNotFoundError: [Errno 2] No such file or directory: 'learning_python.txt'
Steps to reproduce:
I am trying to run a very simple Python program in VS Code. In the same subfolder I have the two following files:
- 10-1_learning_python.py
- learning_python.txt
This is the code in «10-1_learning_python.py»:
filename = 'learning_python.txt'
with open(filename) as file_content:
content = file_content.read()
print(content)
When running the code I get this error:
FileNotFoundError: [Errno 2] No such file or directory: ‘learning_python.txt’
This code works (using the very same directory and files) if I run it in other applications such as SublimeText.
Environment data
I am using macOS Catalina 10.15.5.
My VS Code version is as follows:
Version: 1.45.1
Commit: 5763d909d5f12fe19f215cbfdd29a91c0fa9208a
Date: 2020-05-14T08:33:47.663Z
Electron: 7.2.4
Chrome: 78.0.3904.130
Node.js: 12.8.1
V8: 7.8.279.23-electron.0
OS: Darwin x64 19.5.0Value of the
python.languageServer
setting:Microsoft
filename = r'''C:UsersPythonPython35-32lessonscharper_7exp_1_read_text_from_filecharper_7test.txt'''
try:
text_file = open( filename, "r", encoding = 'utf-8')
print(text_file.read(2))
except OSError as f:
print('ERROR: ',f)
-
Вопрос заданболее трёх лет назад
-
8492 просмотра
Пригласить эксперта
Why you are not using relative path: Что в переводе используйте относительные пути. Я думаю беда где-то в этом.
path = '/Users/Fractal/Desktop/file.txt'
try:
file = open(path)
except OSError as e:
pass
Настоятельно рекомендую использовать Unix систему.
filename = r'C:UsersPythonPython35-32lessonscharper_7exp_1_read_text_from_filecharper_7test.txt'
with open( filename, "r", encoding = 'utf-8') as text_file:
print(text_file.read(2))
А если поменять слово charper_7 на chapter_7, лучше не станет? И, естественно, кавычки лишние убрать — оставить одну в начале после ‘r’ и одну в конце. И второе вхождение charper_7 (chapter_7) не лишнее?
На винде давно не писал, попробуй в пути везде двойной слэш прописать.
ответ нашел!
Проблема была в том, что файл я назвал test.txt, а питон .txt расширение, написанное мною, не считал за расширение. По этому правильно писать: test.txt.txt и все работает.
Всем спасибо, кто пытался помочь
тоже столкнулся с этим на винде 10 в консоле. Решил, только когда от относительных путей (которыми пользовался в iPython ноутбуке и в отладчике на Spyder) перешел к абсолютным путям
-
Показать ещё
Загружается…
05 июн. 2023, в 18:42
10000 руб./за проект
05 июн. 2023, в 18:26
1000 руб./за проект
05 июн. 2023, в 17:51
2800 руб./в час