Forced to enter full pathname every time instead of just file name

541 views Asked by At

Every time I try to do an action such as running a program in the VScode Terminal (also happens in PyCharm) I have to enter in the full pathname instead of just the file name. For example, instead of just doing python3 test.py to run a program, I have to enter in python3 /Users/syedrishad/Desktop/Code/test.py.

Now, this is annoying and all but it doesn't bother me too much. What does bother me is when my program is trying to pull/ open files from somewhere else. If I wanted an image call Apple.jpeg, instead of just typing in Apple.jpeg, I'd have to go and find the full pathname for it. If I were to upload a piece of code doing this to someplace like GitHub, the person who'd want to test this code out for themselves will have to go in and replace each pathname with just the file name or it won't work on their computer. This problem has been going on for a while, and I sadly haven't found a solution to this. I would appreciate any help I get. I'm also on a Mac if that makes a difference.

2

There are 2 answers

0
Yep Yep On

You could use os and sys that gives you the full path to the folder of the python file.
Sys gives you the path and os gives you the possibility to merge it with the file name.

import sys, os
print(sys.path[0]) # that is the path to the directory of the python file
print(sys.path[0]+'/name.txt') #full path to the file
print(os.path.join(sys.path[0],'name.txt')) # os.path.join takes two parameters and merges them as one path using / but the line above is also fine
0
Jill Cheng On

In VS Code, its internal terminal is in the currently opened project folder by default. Therefore, when you use the command "python file_name.py" to run the file, the terminal cannot find the file that exists in the inner folder. Therefore, in addition to using the file path, we can also add related settings to help it find the file.

Run: When using the run button to execute the file, we can add the following settings in "settings.json", it will automatically enter the parent folder of the executed file.

"python.terminal.executeInFileDir": true,

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

enter image description here

debug: For debugging code, we need to add the following settings in "launch.json":

 "cwd": "${fileDirname}",

enter image description here