Errno 2 no such file or directory python как исправить pycharm

I am trying to run a simple Hello World code in pycharm using Python. I have moved the file to another folder. So, I have changed the interpreter location I am getting the following error. This problem has nothing to do with interpreter as you can see in the second image, the interpreter is the correct one and I am able to run it from command prompt.

C:UsersbitanAppDataLocalProgramsPythonPython38-32python.exe: can’t open file ‘C:/Python/Free Code Camp/Learning’: [Errno 2] No such file or directory

Process finished with exit code 2″

Error Image
Interpreter Location Change

I am new to Pycharm/Python. Any help is appreciated.

asked Aug 23, 2020 at 4:55

Economics User's user avatar

Economics UserEconomics User

91 gold badge1 silver badge5 bronze badges

4

go to cmd prompt and type cd <path/of/your/python/file>

then type python3 file_name.py

hope it works. if you get an error comment it.

answered Aug 23, 2020 at 5:56

Ujjwal Kar's user avatar

2

при запуске файла в PyCharm вылезает ошибка python.exe: can’t open file »: [Errno 2] No such file or directory


  • Вопрос задан

    более двух лет назад

  • 3630 просмотров

Не найден файл или директория

Попробуй cделать:
1. Проверьте правильность написания пути к файлу. Возможно его там нет.
2. Запусти PyCharm от имени администратора.
3. Переименуй файл, удали его копии (если есть)

Пригласить эксперта


  • Показать ещё
    Загружается…

25 мая 2023, в 05:30

1000 руб./за проект

25 мая 2023, в 05:14

5000 руб./за проект

25 мая 2023, в 02:38

1000 руб./за проект

Минуточку внимания

Уведомления

  • Начало
  • » Python для новичков
  • » Ошибка IOError: [Errno 2] No such file or directory:

#1 Май 1, 2019 21:39:31

Ошибка IOError: [Errno 2] No such file or directory:

Доброго времени суток!

Я новичок в python. Хотел бы узнать что неправильно настроено в pycharm (я так полагаю дело в кодировке).
Почему он выдает ошибку: IOError: No such file or directory:
При таком коде:

 #! /usr/bin/env python
# -*- coding: utf-8 -*-
# import load_workbook
from openpyxl import load_workbook
# set file path
filepath = 'c:/Users/Андрей/Download/data.xlsx'
# load demo.xlsx
wb = load_workbook(filepath)
# select demo.xlsx
sheet = wb.active
# set value for cell A1=1
sheet['L1'] = 1

Полный текст ошибки:

 C:UsersАндрейPycharmProjectsprojectvenvScriptspython.exe C:/Users/Андрей/PycharmProjects/project/from_excel.py
Traceback (most recent call last):
  File "C:/Users/������/PycharmProjects/project/from_excel.py", line 11, in <module>
    wb = load_workbook(filepath)
  File "C:Python27libsite-packagesopenpyxlreaderexcel.py", line 311, in load_workbook
    data_only, keep_links)
  File "C:Python27libsite-packagesopenpyxlreaderexcel.py", line 126, in __init__
    self.archive = _validate_archive(fn)
  File "C:Python27libsite-packagesopenpyxlreaderexcel.py", line 98, in _validate_archive
    archive = ZipFile(filename, 'r')
  File "C:Python27Libzipfile.py", line 779, in __init__
    self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'c:/Users/xd0x90xd0xbdxd0xb4xd1x80xd0xb5xd0xb9/Download/data.xlsx'
Process finished with exit code 1

Отредактировано Dominus_tempus (Май 1, 2019 21:44:25)

Офлайн

  • Пожаловаться

#2 Май 1, 2019 23:31:18

Ошибка IOError: [Errno 2] No such file or directory:

Dominus_tempus
что неправильно настроено в pycharm

:) Две ошибки:
1 Он установлен на неправильную операционную систему WINDOWS в которой используется одновременно куча кодировок и не всегда понятно где какая.
2. В нем используется python 2.x в котором чуть сложнее разбираться в кодировках.

Можно поправить то что есть (писать u“…”или все-же перейти на python 3, разобраться в какой кодировке у вас скрипт, разобраться как настроить кодировку в pycharm редакторе и консоли и в какой кодировке надо имя для ОС передавать), но думаю вам будет гораздо проще, пока вы не перешли на unix не делать папок и файлов с русскими буквами.

p.s.
Если у вас имя текущего пользователя в винде сделано по русски, то тогда отказы различных пакетов будут случаться регулярно, хоть и не очень часто.

Отредактировано doza_and (Май 1, 2019 23:36:45)

Офлайн

  • Пожаловаться

#3 Май 2, 2019 22:28:10

Ошибка IOError: [Errno 2] No such file or directory:

doza_and
Две ошибки:
1 Он установлен на неправильную операционную систему WINDOWS в которой используется одновременно куча кодировок и не всегда понятно где какая.
2. В нем используется python 2.x в котором чуть сложнее разбираться в кодировках.

Насчет ошибок, поменял имя в системе имя на англ. и переустановил python на python 3.7.
Выдает ошибку. Прошу помочь.

 C:UsersAndrewPycharmProjectsprojectvenvScriptspython.exe C:/Users/Andrew/PycharmProjects/project/excel.py
Traceback (most recent call last):
  File "C:/Users/Andrew/PycharmProjects/project/excel.py", line 11, in <module>
    wb = load_workbook(filepath)
  File "C:UsersAndrewAppDataLocalProgramsPythonPython37libsite-packagesopenpyxlreaderexcel.py", line 311, in load_workbook
    data_only, keep_links)
  File "C:UsersAndrewAppDataLocalProgramsPythonPython37libsite-packagesopenpyxlreaderexcel.py", line 126, in __init__
    self.archive = _validate_archive(fn)
  File "C:UsersAndrewAppDataLocalProgramsPythonPython37libsite-packagesopenpyxlreaderexcel.py", line 98, in _validate_archive
    archive = ZipFile(filename, 'r')
  File "C:UsersAndrewAppDataLocalProgramsPythonPython37libzipfile.py", line 1204, in __init__
    self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'c:/Users/Andrew/Download/data.xlsx'
Process finished with exit code 1

Офлайн

  • Пожаловаться

#4 Май 2, 2019 22:44:12

Ошибка IOError: [Errno 2] No such file or directory:

замените

 filepath = 'c:/Users/Andrew/Download/data.xlsx'

на

 filepath = r'C:UsersAndrewDownloaddata.xlsx'

Отредактировано marvellik (Май 2, 2019 22:45:55)

Офлайн

  • Пожаловаться

#5 Май 3, 2019 07:06:58

Ошибка IOError: [Errno 2] No such file or directory:

marvellik
замените

Да не должно это влиять.
Теперь надо проверить есть ли файл. C:UsersAndrewDownloaddata.xlsx
можно попробовать

или

 import pathlib
for i in Path("c:/Users/Andrew/Download").glob("*.xlsx"):
    print(i)

или

 import pathlib
for i in Path("c:/Users/Andrew/Download").glob("*.*"):
    print(i)

Рекомендую поставить far manager чтобы было видно что в папке, как именно оно называется и что пишет питон в консоль и чтобы была понятна текущая директория..

Отредактировано doza_and (Май 3, 2019 07:07:55)

Офлайн

  • Пожаловаться

#6 Май 3, 2019 21:12:45

Ошибка IOError: [Errno 2] No such file or directory:

Всем спасибо за помощь!

Нашел в чем ошибка: ‘CUsers/Andrew/Downloads/data.xlsx’
Слово загрузки
А что касается изменить имя пользователя, то это однозначно нужно было делать

Офлайн

  • Пожаловаться

  • Начало
  • » Python для новичков
  • » Ошибка IOError: [Errno 2] No such file or directory:

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 👇.

This is a common error when you using Python to develop, almost everyone who learns python has encountered it.

The complete error message is as follows:

Traceback (most recent call last):
  File "/Users/clay/Projects/PythonProjects/python_children_edu/test.py", line 1, in <module>
    open("data.txt", 'r', encoding="utf-8").read(
FileNotFoundError: [Errno 2] No such file or directory: 'xxx.txt'

According to the error message, we can see the reason for this error is that we want to use python to access a file or folder, but the path we provided does not have this file or folder.


Problem recurrence

This is a sample code that repeat the error.

There is no syntax error, but the file cannot be found through the file path.

open("data.txt", 'r', encoding="utf-8").read()

Output:

Traceback (most recent call last):
  File "/Users/clay/Projects/PythonProjects/python_children_edu/test.py", line 1, in <module>
    open("data.txt", 'r', encoding="utf-8").read(
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'

Solution

As explained earlier, there is no problem with the syntax of the program. So the only thing we can do is to check if the path is wrong or the file name is misspelled.

After the correction, the file can probably be read.


References

  • https://docs.python.org/3/library/exceptions.html
  • https://stackoverflow.com/questions/17658856/why-am-i-getting-a-filenotfounderror

  • [Solved][Python] IndexError: list index out of range
  • [Solved] Python SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 0-5: truncated UXXXXXXXX escape

Понравилась статья? Поделить с друзьями:
  • Как найти человека на различных сайтах
  • Печь гуча лава дымит как исправить
  • Как найти минерал кварц
  • Как найти на сайтах вузов
  • Underground 2 как найти скрытые гонки