pythonfilevisual-studio-code

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


Solution

  • 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