- Can’t open file ‘main.py’: [Errno 2] No such file or directory
- Ошибка FileNotFoundError: [Errno 2] No such file or directory
- 1 ответ 1
- Python can’t open file “No such file or directory”
- python: no such file or directory error
- 5 Answers 5
- Not the answer you’re looking for? Browse other questions tagged python excel xlrd or ask your own question.
- Related
- Hot Network Questions
- Subscribe to RSS
- Can’t open file ‘main.py’: [Errno 2] No such file or directory
Can’t open file ‘main.py’: [Errno 2] No such file or directory
Открытие файла, ошибка [Errno 2] No such file or directory
Помогите, пожалуйста. Не могу разобраться в работе с файлами. Открытие файла, как я понимаю: f =.
ImportError: libtk8.6.so: cannot open shared object file: No such file or directory
Здравствуйте! Хотел поработать с Tkinter, а он мне выдал: Traceback (most recent call last): .
Ошибка [Errno 2] No such file or directory
Привет. Пытаюсь установить библиотеку для питона с гитхаба — Vk_api. В официальной нет поддержки.
ОК. Положи файл рядом с исполняемым и вместо пути укажи только имя файла
Добавлено через 27 секунд
И r убери
Добавлено через 2 минуты
python -V
Что пишет?
Добавлено через 1 минуту
Похоже XY problem.
DmFat, ах ты ж, точно. Тогда ясно все.
exampleNew, покажи полный код программы, полный код ошибки, скрин расположения скрипта и файла
Не надо ставить либы и тем более проекты создавать в системных и юзерских папках, создай ты c:/projects и там экспериментируй, а то может винда не дает лезть
exampleNew,
У тебя нет файла main.py в твоем каталоге C:\Users\prost.
Видишь? У меня нет файл 1.py в директории пользователя. Поэтому и ошибка.
Если твой mian.py находится в C:\Users\prost\OneDrive\Рабочий стол\Степа\progamma, то почему ты его не запускаешь с указанием полного пути в консоли cmd? Или без перехода в данную директорию?
Добавлено через 2 минуты
Это так?
C:\Users\prost>python C:\progamma\main.py
Добавлено через 2 минуты
Вот так?
C:\Users\prost>python C:\progamma\main.py
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Py2exe error: [Errno 2] No such file or directory:
Здравствуйте! При создании exe файла из исходника выскакивает ошибка. Создал 2 файла: test.py и.
fatal error C1083: Cannot open include file: ‘Date.h’: No such file or directory
Всем добрый вечер! У меня проблема. Мне нужно, чтобы мой класс содержал обьект другого класса как.
Ошибка fatal error C1083: Cannot open include file: ***: No such file or directory
Помогите пожалуйста исправить ошибку. При компиляции возникает вот такая беда. подробности в.
Ошибка FileNotFoundError: [Errno 2] No such file or directory
Командная строка выдает ошибку FileNotFoundError: [Errno 2] No such file or directory , подробнее на скрине (столкнулся с такой проблемой, изучая учебник Лутца по Python и не могу сдвинуться в изучении языка из-за этого)
Буду признателен за помощь.
1 ответ 1
Есть различные способы задать путь к файлу или папке:
c:\python370\script1.py — абсолютный путь
script1.py — относительный путь, задается относительно текущей рабочей директории. В данном случае файл должен находиться в текущей директории.
В вашем случае текущая директория C:\Users\Acer , вы пытаетесь открыть файл script1.py , но он у вас находится не в этой директории, а в c:\python370 . Поэтому просто по имени файла вы файл не откроете, нужно указать полный (абсолютный) путь:
Или запускать Python сразу из нужной директории — двойным кликом по файлу python.exe в папке c:\python370 или в окне cmd сначала перейти в директорию, где лежит нужный файл, потом запустить python, и пробовать открыть файл.
C:\Users\Михаил — это текущая директория.
Меняем текущую директорию такой командой (опять же в cmd, до запуска python):
В python текущую директорию можно узнать, выполнив команды:
cwd — сокращение от current working directory — текущая рабочая директория.
Поменять текущую директорию из Python можно так:
В итоге, если текущая рабочая директория не совпадает с директорией, где лежит файл, то вы не сможете открыть файл просто по его имени. Нужно или указать полный (абсолютный) путь, или изменить текущую директорию.
Кстати, чтобы не экранировать обратные слеши в строке пути, можно использовать «сырые» (raw) строки, с буквой r перед кавычками, например:
Python can’t open file “No such file or directory”
I am on for-working.py file, and am trying to access the lines.txt file within the same working directory. But I get error
No such file or directory: ‘lines.txt’
Does python need to have an absolute path when opening files?
why doesn’t this relative path work here?
Running python 3.6
EDIT ^1 I’m running visualstudio code with the python package extension by Don Jayamanne, and «Code Runner» package to compile/execute python code
EDIT ^2 Full error:
EDIT ^3 checking sys.path
produces this information:
EDIT ^4 checking os.getcwd()
Well its definitely not in the right subdirectory (needs to cd 07 loops folder, that narrows the issue down
EDIT ^5 what is in lines.txt file
My lines.txt file i am opening looks like this. No extra whitespace or anything at start
IN SUMMARY
Visual studio code’s Code runner extension needs to be tweaked slightly to open files within a subdirectory so any of the below answers would provide a more robust solution to be independent of any extension / dependencies with the IDE
Is most useful for diagnosing problem to the current directory python interpreter sees
python: no such file or directory error
I’m new to python. I’m trying to read a MS excel file that is in the same directory as my python script. Running the above code gives me a no such file or directory error.
I’ll provide more information if needed.
Edit: code with full path upon request
with corresponding error message
5 Answers 5
You’re getting hurt by string escapes. \ is an escape character for Python strings, so Python is attempting to find the \P and \u escape codes (among other things), which aren’t going to be what you want.
The fix is either to escape the \ by changing the path to «D:\Python_Scripts\univ_list.xls», or to switch the string to an r»» (i.e. r»D:\Python_Scripts\univ_list.xls» ) string, which doesn’t honor backslashes.
If python says you can’t find a file, there are a couple steps you should take. The first is to make sure that the file exists. The first step is to make sure it’s spelled correctly. Then, as suggested by AdamKG, make sure python can see it:
just for supplement
Replaceing \ to / or \\ will be fine:
Because in Python strings, the backslash «\» is a special character, also called the «escape» character. You can read more in the document.
if you need \ , actually you need \\ .
The issue is that PyScripter sets the current directory. This is not the directory that your excel or python files is in (It will be probably be either your home, c:\ or the directory Pyscriper is in ( use os.getcwd() to get what it is).
Thus the fix is to provide the full path — but as shown in the other answers and comments this needs to be the string in raw form as Windows uses \ which do not mix well with the programming use of \ as an escape character in strings.
works perfectly well except that I need to replace xls with xlsx.
Not the answer you’re looking for? Browse other questions tagged python excel xlrd or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Can’t open file ‘main.py’: [Errno 2] No such file or directory
Открытие файла, ошибка [Errno 2] No such file or directory
Помогите, пожалуйста. Не могу разобраться в работе с файлами. Открытие файла, как я понимаю: f =.
ImportError: libtk8.6.so: cannot open shared object file: No such file or directory
Здравствуйте! Хотел поработать с Tkinter, а он мне выдал: Traceback (most recent call last): .
Ошибка [Errno 2] No such file or directory
Привет. Пытаюсь установить библиотеку для питона с гитхаба — Vk_api. В официальной нет поддержки.
ОК. Положи файл рядом с исполняемым и вместо пути укажи только имя файла
Добавлено через 27 секунд
И r убери
Добавлено через 2 минуты
python -V
Что пишет?
Добавлено через 1 минуту
Похоже XY problem.
DmFat, ах ты ж, точно. Тогда ясно все.
exampleNew, покажи полный код программы, полный код ошибки, скрин расположения скрипта и файла
Не надо ставить либы и тем более проекты создавать в системных и юзерских папках, создай ты c:/projects и там экспериментируй, а то может винда не дает лезть
exampleNew,
У тебя нет файла main.py в твоем каталоге C:\Users\prost.
Видишь? У меня нет файл 1.py в директории пользователя. Поэтому и ошибка.
Если твой mian.py находится в C:\Users\prost\OneDrive\Рабочий стол\Степа\progamma, то почему ты его не запускаешь с указанием полного пути в консоли cmd? Или без перехода в данную директорию?
Добавлено через 2 минуты
Это так?
C:\Users\prost>python C:\progamma\main.py
Добавлено через 2 минуты
Вот так?
C:\Users\prost>python C:\progamma\main.py
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Py2exe error: [Errno 2] No such file or directory:
Здравствуйте! При создании exe файла из исходника выскакивает ошибка. Создал 2 файла: test.py и.
fatal error C1083: Cannot open include file: ‘Date.h’: No such file or directory
Всем добрый вечер! У меня проблема. Мне нужно, чтобы мой класс содержал обьект другого класса как.
Ошибка fatal error C1083: Cannot open include file: ***: No such file or directory
Помогите пожалуйста исправить ошибку. При компиляции возникает вот такая беда. подробности в.