Relative File Path is not recognized by Python in VSCode

Question:

When I am using Absolute path the code is working fine but using relative path throwing FileNotFoundError in python.

 f = open("Input.txt","r")

enter image description here

Asked By: Hmm

||

Answers:

Your python file is executed by the terminal. You can clearly see that your terminal is at the folder ...DesktopcsPythonmyproject. Since the file "Input.txt" does not exist relative to the path of your terminal, you are getting this error. (That is, the path ...DesktopcsPythonmyprojectInput.txt does not exist)

A simple solution would be to use absolute path in your python file instead of the relative path.

Another cheap solution is to use the terminal, go to the correct folder and run your file, as intended by God.

If you really want to dedicate a single button for running, you can try the following:

EDIT: Okay, I understand you are using the "Run button" at top of python files to run.

You only need to set the setting python.terminal.executeInFileDir to true.

In Settings, search for python.terminal.executeInFileDir and mark it. That should be what you need.
enter image description here

Answered By: AzuxirenLeadGuy

A quick solution to use relative paths can be to right click on the file, copy relative path and replace "" with "/". You can do it manually or with the function .replace("","/").

"routeinput.txt".replace("","/")

Answered By: Manolo Morato
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.