Hmm
Hmm

Reputation: 33

Relative File Path is not recognized by Python in VSCode

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

Upvotes: 2

Views: 21211

Answers (3)

Maaza
Maaza

Reputation: 87

The better approach is by using os.path.relpath as below.

os.chdir(os.path.dirname(os.path.realpath(__file__)))

this link explains it better.

https://www.reddit.com/r/vscode/comments/t2svvv/vs_code_needing_full_path_to_locate_files/

Upvotes: 1

Manolo Morato
Manolo Morato

Reputation: 1

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("","/").

"route\input.txt".replace("","/")

Upvotes: 0

AzuxirenLeadGuy
AzuxirenLeadGuy

Reputation: 2860

Your python file is executed by the terminal. You can clearly see that your terminal is at the folder ...Desktop\cs\Python\myproject\. Since the file "Input.txt" does not exist relative to the path of your terminal, you are getting this error. (That is, the path ...Desktop\cs\Python\myproject\Input.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

Upvotes: 13

Related Questions