0 / 0 / 0 Регистрация: 03.06.2021 Сообщений: 2 |
|
1 |
|
30.11.2021, 21:17. Показов 6097. Ответов 5
Visual Studio не хочет запускать мой код. Запускаю в 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 |
1728 / 967 / 199 Регистрация: 22.02.2018 Сообщений: 2,694 Записей в блоге: 6 |
|
30.11.2021, 22:00 |
2 |
Jesuslovesyou, Вы не указали версию Visual Studio. В последней версии Visual Studio есть такой дефект, она не видит настройки питона в PATH.
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 |
Вы не указали версию Visual Studio. Прошу прощения, версия – 1.62. Насчет PyCharm’а, я рано обрадовался, что там код работает. В PyCharm я только запускал скопированный код, который автоматически записывался в файл main.py. Этот файл – main.py – был автоматически создан в папке с PyCharm’ом и с его запуском проблем не должно быть, а в VisualStudio, я открывал файл из папки на рабочем столе. Но в любом случае, раньше я запускал в VS файлы с рабочего стола и всё отлично работало. Проблема точно в “пути” к файлу, но как её решить, пока не понимаю
0 |
1728 / 967 / 199 Регистрация: 22.02.2018 Сообщений: 2,694 Записей в блоге: 6 |
|
30.11.2021, 23:18 |
5 |
AlexMarkov, Да, опечатка. Должно быт сокращение от path, где отбрасывается гласная “а”. Я же там дальше написал, как называется у меня файл, и там расширение правильное. Добавлено через 19 минут
но как её решить, пока не понимаю Я написал выше как. Создайте файл myconfig.pth. Разместите его туда, где у Вас python.exe , основная папка питона.
1 |
1728 / 967 / 199 Регистрация: 22.02.2018 Сообщений: 2,694 Записей в блоге: 6 |
|
01.12.2021, 08:08 |
6 |
версия – 1.62 Вы наверное что то путаете. У меня Microsoft Visual Studio Community 2019.
0 |
I have just started to learn Python and I watched this video tutorial –
https://www.youtube.com/watch?v=rioXu6EBN0s
when I attempted to create my own .hmtl file using the method in the video I got this error –
FileNotFoundError: [Errno 2] No such file or directory:
this is what I have entered into Visual Studio-
my_variable = "<html><body><p>This is a paragraph.</p><p>This is another paragraph.</p></body></html>"
my_html_file = open("C:UsersLiamDocumentsCodingMy FilesPythonMy Tests/my_html_file.html" "w")
my_html_file.write(my_variable)
I have tried changing to
/Users/Liam.Documents/Coding/My Files/Python/My Tests/
/my_html_file.html
but it hasn’t worked, any suggestions would be greatly appreciated.
liam
asked Nov 3, 2017 at 7:44
3
Whenever you need to debug, you need to change the path of the file to open it in debug mode by simply:
- Going to the explorer
- Right click on the file and click on copy relative path
- Put that path in open
Also I saw that you put this in your code:
my_html_file = open("C:UsersLiamDocumentsCodingMy FilesPythonMy Tests/my_html_file.html" "w")
You’re missing a coma before the w, it should be like this:
my_html_file = open("C:UsersLiamDocumentsCodingMy FilesPythonMy Tests/my_html_file.html","w")
edit: Lol, now I saw that someone else answer your question by replying, anyway, that should help others too! at least…
answered Aug 17, 2020 at 2:34
1
The reason for this is that you are missing a comma between the filename and the mode that you are using to open the file. Due to this, the interpreter is trying to read the file, which will lead to an error if the file you are requesting does not exist.
answered Aug 17, 2020 at 2:54
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
Visual Studio Code under Python error [errno 2] No Such File or Directory
tags: python VS code Natural language processing
VS Code is a lightweight IDE, which is very convenient. When you debug Python code today, an error [Errno 2] No Such File or Directory (see the figure below). In fact, this file is in the same folder of the main program.
Solution (see below): 1, open the settings;
Copyright Complaint
Spam Report
Intelligent Recommendation
Yum: [Errno 5] [Errno 2] No such file or directory error
Transfer from: http: //blog.51cto.com/chaichuan/2083574 When the software is installed yum, yum repository can connect, but fails to download and install, being given as follows This is because…
Python open: FileNotFoundError: [Errno 2] No such file or directory
Using python function to create txt open time: Error: FileNotFoundError: [Errno 2] No such file or directory: ‘Volumes/WorkPlace/seg_pic/train_mask.txt’ the reason: using open or create a …
The solution to “FileNotFoundError: [Errno 2] No such file or directory” in python
The solution to “FileNotFoundError: [Errno 2] No such file or directory” in python 1. Reason: This is because in Vscode, the path in python is located relative to the working directory. Ther…
In Python: FilenotFounderror: [Errno 2] No Such File or Directory:
Recently introduced to the log module in Python: logging to add logs, but find out the error when the traffic path to introduce the log: FileNotFoundError: [Errno 2] No such file or directory All of m…
Win10 Python IOError: [Errno 2] No such file or directory
Report: Why can’t you find it in a clear catalog. Even at the beginning of the code# -*- coding: utf-8 -*- It can’t be resolved. possible reason: You use Python2, support for the path containing Chine…
More Recommendation
Python FileNotFoundError: [Errno 2] No such file or directory: ‘XXX‘
content Foreword Make a mistake 1. Use pycharm to create a new Python project 2. Simple project structure 3. Add the corresponding content 4. Execute the code and reproduce the error The cause of erro…
[Errno 2] No such file or directory
Centos7.5 ansible command execution error problem: the reason: Solution:…
New Project django error python: can not open file ‘manage.py’: [Errno 2] No such file or directory
Today encounter this problem has been given, the results do not know how, the way I can find online are tried, or not Input terminal of the terminal pycharm below command: cd mysite then enter it Then…
Create database python: can‘t open file ‘manage.py’: [Errno 2] No such file or directory error
Run the code when creating the database operation result the reason There is no manage.py file under the directory. Solution Find the directory where the manage.py file is located, cd in, and enter py…
Python file reading error FileNotFoundError: [Errno 2] No such file or directory:, by the way, learn the usage of slash/ and backslash
Python file reading error FileNotFoundError: [Errno 2] No such file or directory:, by the way, learn the usage of slash/ and backslash: I recently learned about file reading and Chinese word segmenta…
Table of Contents
Hide
- Python FileNotFoundError: [Errno 2] No such file or directory
- Example FileNotFoundError
- Misspelled file name
- Invalid file path or directory path
- Using a relative path
- Solution to FileNotFoundError: [Errno 2] No such file or directory
In Python, when you reference a file, it needs to exist. Otherwise, Python will return a FileNotFoundError: [Errno 2] No such file or directory.
In this tutorial, let’s look at what is FileNotFoundError: [Errno 2] No such file or directory error means and how to solve this in your code.
Python will raise FileNotFoundError when you use the OS library and try to read a file or write a file that does not exist using an open()
statement.
It is, of course, excluding you are creating a new file and writing content to the file. Any error message which states FileNotFoundError means that Python cannot find the path of the file you are referencing.
Example FileNotFoundError
The below code will list all the files in a specified folder. We will be using the OS module and os.listdir()
method to get a list of files in the specified folder.
import os
for f in os.listdir("/etc"):
print(f)
Output
Traceback (most recent call last):
File "Main.py", line 2, in <module>
for f in os.listdir("/etc/test"):
FileNotFoundError: [Errno 2] No such file or directory: '/etc/test'
Now you can see that Python is throwing FileNotFoundError: [Errno 2] No such file or directory since the folder reference is wrong here.
The possible reasons for this error could be as follows.
Misspelled file name
The error will often occur due to misspelled filenames, so providing the correct file name would solve the issue.
Invalid file path or directory path
Sometimes you might give a wrong file path or directory path which does not exist. It usually happens even with the network path when it’s unreachable. So ensure that the file path is correct and if you are placing the file in the network path, make sure it’s reachable and accessible.
Using a relative path
If you use a relative path, the file would be searched in the current working directory and not in the original path. So ensure you give an absolute path of the file to resolve the error.
Solution to FileNotFoundError: [Errno 2] No such file or directory
We will correct our above code by referencing the proper directory where the file exists. This time, we will also use an absolute path instead of a relative path to ensure it’s referencing the correct directory.
import os
for f in os.listdir("C:/Projects/Tryouts/etc"):
print(f)
Output
python.txt
index.md
Python Data Science Ebook.pdf
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.