Error pycharm no such file or directory

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

Уведомления

  • Начало
  • » 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:

Like any programming language, an error in python occurs when a given code fails to follow the syntax rules. When a code does not follow the syntax, python cannot recognize that segment of code, so it throws an error. Errors can be of different types, such as runtime error, syntax error, logical error, etc. IOError errno 2 no such file or directory is one such type of error. Let us first understand each individual term of the error.

Note : Starting from Python 3.3, IOError is an aliases of OSError

What is IOError?

An IOError is thrown when an input-output operation fails in the program. The common input-output operations are opening a file or a directory, executing a print statement, etc. IOError is inherited from the EnvironmentError. The syntax of IOError is:

IOError : [Error number] ‘Reason why the error occurred’: ‘name of the file because of which the error occurred’

Examples of IOError are :

  • Unable to execute the open() statement because either the filename is incorrect or the file is not present in the specified location.
  • Unable to execute the print() statements because either the disk is full or the file cannot be found
  • The permission to access the particular file is not given.

What is errno2 no such file or directory?

The ‘errorno 2 no such file or directory‘ is thrown when you are trying to access a file that is not present in the particular file path or its name has been changed.

This error is raised either by ‘FileNotFoundError’ or by ‘IOError’. The ‘FileNotFoundError’ raises ‘errorno 2 no such file or directory‘ when using the os library to read a given file or a directory, and that operation fails.

The ‘IOError’ raises ‘errorno 2 no such file or directory‘ when trying to access a file that does not exist in the given location using the open() function.

Handling ‘IOError [errorno 2] no such file or directory’

‘IOError errorno 2 no such file or directory‘ occurs mainly while we are handling the open() function for opening a file. Therefore, we will look at several solutions to solve the above error.

We will check if a file exists, raise exceptions, solve the error occurring while installing ‘requirements.txt,’ etc.

Checking if the file exists beforehand

If a file or a directory does not exist, it will show ‘IOError [errorno 2] no such file or directory’ while opening it. Let us take an example of opening a file named ‘filename.txt’.

The given file does not exist and we shall see what happens if we try to execute it.

Since the above text file does not exist, it will throw the IOError.

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    f = open('filename.txt')
IOError: [Errno 2] No such file or directory: 'filename.txt'

To avoid the above error from being thrown, we will use several methods which will first check if the file exists or not. It will execute the open() function only if the file exists.

We have two modules containing functions for checking if a file exists.

  1. OS Module
  2. Pathlib Module

Using the OS Module

In the os module, there are three functions which can be used:

  • os.path.isfile()
  • os.path.isdir()
  • os.path.exists()

To solve the IOError, we can use either of the above function in a condition statement. We will pass the pathname of the file as an argument to the above functions.

If the file or the directory exists, the function shall return True else False. Bypassing either of the above functions as the conditional statement ensures that python will open a file only if it exists, thus preventing an error from occurring.

We will use os.path.isfile() when we want to check if a file exists or not, os.path.isdir() to check if a directory exists or not and os.path.exists() to check if a path exists or not.

Since we want to check for a file, we can use either the os.path.isfile() function or os.path.exists() function. We shall apply the function to the above example.

import os

path_name = "filename.txt"

if os.path.isfile(path_name):
  print("File exists")
  f = open(path_name)
  #Execute other file operations here
  f.close()
  
else:
  print("File does not exist! IOError has occured")

First, we have imported the os module. Then we have a variable named ‘path_name‘ which stores the path for the file.

We passed the path_name as an argument to the os.path.isfile() function. If the os.path.isfile() function returns a true value. Then it will print “File exists” and execute the other file operations.

If the file does not exist, then it will print the second statement in the else condition. Unlike the previous case, here, it will not throw an error and print the message.

File does not exist! IOError has occured

Similarly, we can also use os.path.exists() function.

Using the pathlib module

The pathlib module contains three functions – pathlib.Path.exists(), pathlib.Path.is_dir() and pathlib.Path.is_file().

We will use pathlib.Path.is_file() in this example. Just like the os module, we will use the function in an if conditional statement.

It will execute the open() function only if the file exists. Thus it will not throw an error.

from pathlib import Path
path_name = "filename.txt"
p = Path(path_name)
if p.is_file():
  print("File exists")
  f = open(path_name)
  #Execute other file operations here
  f.close()
  
else:
  print("File does not exist! IOError has occured")

Since the file does not exist, the output is :

File does not exist! IOError has occured

Using try – except block

We can also use exception handling for avoiding ‘IOError Errno 2 No Such File Or Directory’. In the try block, we will try to execute the open() function.

If the file is present, it will execute the open() function and all the other file operations mentioned in the try block. But, if the file cannot be found, it will throw an IOError exception and execute the except block.

try:
    f = open("filename.txt")
    #Execute other operations
    f.close()
except IOError as io:
    print(io)

Here, it will execute the except block because ‘filename.txt’ does not exist. Instead of throwing an error, it will print the IOError.

[Errno 2] No such file or directory: 'filename.txt'

We can also print a user defined message in the except block.

try:
    f = open("filename.txt")
    #Execute other operations
    f.close()
except IOError:
    print("File does not exist. IOError has occured")

The output will be:

File does not exist. IOError has occured

IOError errno 2 no such file or directory in requirements.txt

Requirements.txt is a file containing all the dependencies in a project and their version details.

Basically, it contains the details of all the packages in python needed to run the project. We use the pip install command to install the requirements.txt file. But it shows the ‘IOError errno 2 no such file or directory’ error.

!pip install -r requirements.txt

The thrown error is:

ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt'

To solve the above error, we use the pip freeze command. When we use pip freeze, the output will contain the package along with its version.

The output will be in a configuration that we will use with the pip install command.

pip freeze > requirements.txt

Now, we will try to execute the pip install command again. It will no longer throw errors and all the packages will be installed successfully.

Opening file in ‘w+’ mode

While trying to open a text file, the default mode will be read mode. In that case, it will throw the ‘IOError Errno 2 No Such File Or Directory’ error.

f = open("filename.txt")
f.close()
print("Successful")

The output is:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    f = open("filename.txt")
IOError: [Errno 2] No such file or directory: 'filename.txt'

To solve the error, we can open the file in ‘w+’ mode. This will open the file in both – reading and writing mode. If the file does not exist, it will create a new file, and if the file exists, it will overwrite the contents of the file. This way, it will not throw an error.

f = open("filename.txt", 'w+')
f.close()
print("Successful")

The output is:

Successful

Apart from all the above methods, there are some ways to ensure that the IOError does not occur. You have to ensure that you are giving the absolute path as the path name and not simply the name of the file.

Also, see to that there are no escape sequences in the path name of this file.

For example : In path_name = "C:name.txt ", it will consider the 'n' from 'name.txt' as an escape sequence. 

So, it will not be able to find the file 'name.txt'.

Also, Read

  • How to Solve “unhashable type: list” Error in Python
  • How to solve Type error: a byte-like object is required not ‘str’
  • Invalid literal for int() with base 10 | Error and Resolution
  • How to Solve TypeError: ‘int’ object is not Subscriptable

What is the difference between FileNotFoundError and IOError

Both the errors occur when you are trying to access a file that is not present in the particular file path, or its name has been changed. The difference between the two is that FileNotFoundError is a type of OSError, whereas IOError is a type of Environment Error.


This sums up everything about IOError Errno 2 No Such File Or Directory. If you have any questions, do let us know in the comments below.

Until then, Keep Learning!

Filenotfounderror Errno 2 no such file or directory is a python error always comes when you are not defining proper path for the file or file does not exist in the directory. In this entire tutorial, you will know how to solve Filenotfounderror Errno 2 no such file or directory in an easy way in different scenarios.

Before going to the various scenarios let’s create a sample CSV file using the panda’s library. The file will contain the name and age of the person. Execute the below line of code to create a person.csv file. It is only for demonstration purposes. You can move to cases if you are already getting the problem.

import pandas as pd
data = {"name":["Sahil","Rob","Maya"],"age":[23,67,45]}
df = pd.DataFrame(data)
df.to_csv("person.csv")

It will save the person.csv file to the current working directory of the project.

Case 1: File Name is Incorrect

If you are reading the CSV file with the incorrect name then you will get this Filenotfounderror Errno 2 with no such file or directory error. For example, instead of reading the person.csv filename, I am reading persons.csv. Then you will get this filenotfounderror.

import pandas as pd
df = pd.read_csv("persons.csv")
print(df)

FileNotfounderror on reading the wrong filename

FileNotfounderror on reading the wrong filename

Solution 

Check the name of the file and write the correct filename with its type.

Case 2: Using the OS Library

Filenotfounderror Errno 2 no such file or directory error also comes when you are using the OS Python library and defining the wrong path. For example, I am passing the wrong path for filename “persons.csv”. It will give me an error.

Solution 

Check the path of the working directory and then define the path.

Case 3: Passing the wrong file name or path for the open() method

The third case is when this error comes when you are reading the file using the open() method and passing the wrong filename.

import csv
with open('persons.csv','r') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

FileNotfounderrro on reading the wrong filename using the open() method

FileNotfounderrro on reading the wrong filename using the open() method

Solution :

The solution to this problem, in this case, is very simple. Check the filename of the file you want to open and then pass the exact path for the filename for that file.  To know the current working directory you have to use the os.getcwd(). The error will be solved.

['', 'name', 'age']
['0', 'Sahil', '23']
['1', 'Rob', '67']
['2', 'Maya', '45']

Case 4: Wrong Directory

In most of the cases, Filenotfounderror no such file or directory error comes when you are defining the wrong path for the filename.

import pandas as pd
df = pd.read_csv("/foo/persons.csv")
print(df)

FileNotfounderrro python error due to wrong file path

FileNotfounderrro python error due to wrong file path

Solution

The solution of this case is that if have forgotten the path for the filename then you have to use the OS library. There is a method for finding the path and it is os.getcwd() and then use it with the filename. Execute the following lines of code.

import pandas as pd
import os
cwd = os.getcwd()
df = pd.read_csv(f'{cwd}/person.csv')
print(df)

Now you will get the output.

Solution for FileNotFoundError using the OS Package

Solution for FileNotFoundError using the OS Package

Conclusion

This type of error is mostly annoying to every programmer. They often get this error. These are the cases for various scenarios where its solution is very simple. I hope you have liked this tutorial. If you have any queries then you can contact us for more help.

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

0 / 0 / 0

Регистрация: 03.06.2021

Сообщений: 2

1

30.11.2021, 21:17. Показов 4051. Ответов 5


Visual Studio не хочет запускать мой код.
Пишет:
[Errno 2] No such file or directory

Запускаю в PyCharm’е все отлично работает, а вот VS code и python IDLE запускать не хотят. Подскажите, как исправить ошибку?

Вот, что выдает терминал:

Код

PS C:UsersUserOneDriveРабочий столПрограммированиеPython 3.10Мини-проекты> & C:/Users/User/AppData/Local/Programs/Python/Python39/python.exe "c:/Users/User/OneDrive/абочий 
стол/рограммирование/Python 3.10/ини-проекты/random_8.py"
C:UsersUserAppDataLocalProgramsPythonPython39python.exe: can't open file 'c:UsersUserOneDrive╨░╨▒╨╛╤З╨╕╨╣ ╤Б╤В╨╛╨╗╤А╨╛╨│╤А╨░╨╝╨╝╨╕╤А╨╛╨▓╨░╨╜╨╕╨╡Python 3.10╨╕╨╜╨╕-╨┐╤А╨╛╨╡╨║╤В╤Лrandom_8.py': [Errno 2] No such file or directory
PS C:UsersUserOneDriveРабочий столПрограммированиеPython 3.10Мини-проекты>

На кракозябры из-за кириллицы не смотрите. До этого и с ними всё работало. А потом я полез в PATH, чтобы настроить папку для того, чтобы библиотеки питоновские мог загрузить и после этого начал выдавать такую ошибку. Понимаю, что я скорее всего что-то натворил с «путем» к файлу. Нуждаюсь в вашей помощи

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



1726 / 966 / 198

Регистрация: 22.02.2018

Сообщений: 2,694

Записей в блоге: 6

30.11.2021, 22:00

2

Jesuslovesyou, Вы не указали версию Visual Studio. В последней версии Visual Studio есть такой дефект, она не видит настройки питона в PATH.
Кстати Visual Studio для питона версии 3.8 пишет, что официально не поддерживает эту версию питона, и некоторые новые функции могут работать не правильно.
Но я пока не встречался с проблемами, кроме работы с PATH. Но я решил проблему, с помощью файла .ptf . Создал файл myconfig.pth и указал в нем пути к каталогам, в которых нужно искать файлы, а именно каталог библиотеки и путь к нему.
Почитайте про этот файл у Лутца.
Почему не работает с PATH в IDLE , это загадка. Видимо недоработки версии питона 3.9. Никогда нет полной гарантии, что в последней версии питона, все работает. Поэтому лучше работать с предпоследней версией.
PyCharm созданный именно для работы с питоном, наиболее быстро адаптируется к новым версиям питона, в отличие от Visual Studio, которая ориентирована в первую очередь на линейку С++/C#. К последней версии питона, они адаптируют в последнюю очередь.



1



99 / 86 / 20

Регистрация: 10.09.2019

Сообщений: 708

30.11.2021, 22:21

3

Но я решил проблему, с помощью файла .ptf,Viktorrus, напомните пожалуйста что это за файл, или это файл конфигурации Visual Studio? Понял, это опечатка…pth



0



0 / 0 / 0

Регистрация: 03.06.2021

Сообщений: 2

30.11.2021, 22:58

 [ТС]

4

Цитата
Сообщение от Viktorrus
Посмотреть сообщение

Вы не указали версию Visual Studio.

Прошу прощения, версия — 1.62.

Насчет PyCharm’а, я рано обрадовался, что там код работает. В PyCharm я только запускал скопированный код, который автоматически записывался в файл main.py. Этот файл — main.py — был автоматически создан в папке с PyCharm’ом и с его запуском проблем не должно быть, а в VisualStudio, я открывал файл из папки на рабочем столе. Но в любом случае, раньше я запускал в VS файлы с рабочего стола и всё отлично работало. Проблема точно в «пути» к файлу, но как её решить, пока не понимаю



0



1726 / 966 / 198

Регистрация: 22.02.2018

Сообщений: 2,694

Записей в блоге: 6

30.11.2021, 23:18

5

AlexMarkov, Да, опечатка. Должно быт сокращение от path, где отбрасывается гласная «а». Я же там дальше написал, как называется у меня файл, и там расширение правильное.

Добавлено через 19 минут

Цитата
Сообщение от Jesuslovesyou
Посмотреть сообщение

но как её решить, пока не понимаю

Я написал выше как. Создайте файл myconfig.pth. Разместите его туда, где у Вас python.exe , основная папка питона.
Точно не помню, но помоему у меня были проблемы, разместить там файл, Винда не давала разместить там файл. И мне по моему пришлось давать себе права доступа в эту папку. Но точно не помню. Вобщем нужно в корневую папку питона разместить этот файл. Это обычный текстовый файл созданный блокнотом, в котором прописаны все пути к нужным папкам, где питон будет искать файл.



1



1726 / 966 / 198

Регистрация: 22.02.2018

Сообщений: 2,694

Записей в блоге: 6

01.12.2021, 08:08

6

Цитата
Сообщение от Jesuslovesyou
Посмотреть сообщение

версия — 1.62

Вы наверное что то путаете. У меня Microsoft Visual Studio Community 2019.
После неоднократных обновлений сейчас Версия 16.11.7
До этого у меня стояла Microsoft Visual Studio Community 2017. Она с питоном 3.8 не работает.
Не знаю, появилась ли более свежая версия Microsoft Visual Studio Community, но пока меня и Microsoft Visual Studio Community 2019 устраивает.



0



Понравилась статья? Поделить с друзьями:
  • Error pxvlib file is empty
  • Error please upgrade to the platformio core 6
  • Error please try again confirm the transaction and make sure you are paying enough gas
  • Error please solve captcha correctly перевод
  • Error please set dayz executable location in settings