Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio Code: FileNotFoundError: [Errno 2] No such file or directory

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 
['fij\n', 'feijfaef\n', 'ef\n', 'awef\n', 'awe\n', 'g\n', 'aweg\n', 'ae\n', 'wg\n', 'awe\n', 'h\n', 'aw\n', 'h\n', 'aw\n', 'ef\n', 'aweg\n', 'wea\n', 'gaw\n', 'eg\n', '\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.

like image 744
YoungMin Park Avatar asked Dec 10 '22 06:12

YoungMin Park


2 Answers

First of all, get the directory of the module that is currently running by os.path.dirname(__file__). Then, you can join the relative path of your desire file to this directory path.

from os.path import dirname, join
current_dir = dirname(__file__)
file_path = join(current_dir, "./test.txt")
with open(file_path, 'r') as f:
like image 87
soheil zabihi Avatar answered Jan 29 '23 13:01

soheil zabihi


Try this: enable the below option in your VSCode python setting

When executing a file in the terminal, whether to use execute in the file's directory, instead of the current open folder

like image 26
Armanzarei Avatar answered Jan 29 '23 15:01

Armanzarei