When I load files via Visual Studio Code, VScode can’t find directory.
I can run code without issue with terminal, result is:
young@young-desktop:/media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials/10_RNN/ChatBot$ python text_load_text.py
['fijn', 'feijfaefn', 'efn', 'awefn', 'awen', 'gn', 'awegn', 'aen', 'wgn', 'awen', 'hn', 'awn', 'hn', 'awn', 'efn', 'awegn', 'wean', 'gawn', 'egn', 'n']
But with VScode:
young@young-desktop:/media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials$ cd /media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials ; env "PYTHONIOENCODING=UTF-8" "PYTHONUNBUFFERED=1" /home/young/anaconda3/bin/python /home/young/.vscode/extensions/ms-python.python-2018.6.0/pythonFiles/PythonTools/visualstudio_py_launcher.py /media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials 39707 34806ad9-833a-4524-8cd6-18ca4aa74f14 RedirectOutput,RedirectOutput /media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials/10_RNN/ChatBot/text_load_text.py
Traceback (most recent call last):
File "/media/young/5e7be152-8ed5-483d-a8e8-b3fecfa221dc/text/mycodehtml/pracdl/golbin/TensorFlow-Tutorials/10_RNN/ChatBot/text_load_text.py", line 8, in <module>
with open('test.txt', 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
What causes this issue?
test.txt file originally is intended to be located in ./data/test.txt
So I tested
with open('./data/test.txt', 'r') as f:
But it failed with VScode
So I tried to move test.txt file to working directory with trying:
with open('test.txt', 'r') as f:
and
with open('./test.txt', 'r') as f:
But all failed with VScode.
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.languageServersetting:Microsoft
|
0 / 0 / 0 Регистрация: 03.06.2021 Сообщений: 2 |
|
|
1 |
|
|
30.11.2021, 21:17. Показов 6210. Ответов 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 |
iliasamodin, для того, чтобы установить рабочую директорию для .py программ, то есть. ту директорию, где программа при запуске через vs code будет искать другие файлы и куда она будет сохранять новые, необходимо отметить галочкой следующую настройку: executeInFileDir, или добавить в словарь settings.json следующую строку:
"python.terminal.executeInFileDir": true
Возможно кому-то пригодится 
При запуске программы VS Code выдает ошибку
unable to start debugging unexpected gdb output from command:"-environment-cd C:Users..." ... No such file or directory
Как ее исправить?
launch.json
"configurations": [
{
"name": "g++.exe build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "C:\MinGW\bin\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "g++.exe build active file"
},
{
"name": "g++ build & run active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false, //set to true to see output in cmd instead
"MIMode": "gdb",
"miDebuggerPath": "C:\MinGW\bin\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "g++ build & run active file"
}
]


