Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python change working direcory does not work properly?

Tags:

python

sys

Im new to python and are trying to figure out this for hours.. I want to change the working directory with os in my script by using

os.chdir("~") # not working.

os.getcwd #--> "/home/pi/Documents"

#I want to change into a subfolder I tried following
"subfolder"
"subfolder/"
"~../subfolder"
"/subfolder"

Tried:

sys.path.append. 
like image 223
Felix Avatar asked Mar 07 '23 20:03

Felix


2 Answers

In a shell, ~ refers to the home directory of the invoking user ($HOME).

os.chdir takes a literal directory name as string. So, with just os.chdir("~"), you are trying to cd into the ~ directory relatively (from the current working directory), which does not exist.

You need to use os.path.expanduser to expand the ~ to the value of $HOME beforehand:

os.chdir(os.path.expanduser('~'))

Note that, you need to use os.path.expanduser for ~user references as well, which refers to the $HOME of user.

like image 123
heemayl Avatar answered Mar 15 '23 10:03

heemayl


if you are in the directory /home/pi/Dokuments and you want to go to /home/pi/Dokuments/subfolder, you might want to try the following:

os.chdir(os.path.join(os.getcwd(), "subfolder"))
like image 41
Mohsin Avatar answered Mar 15 '23 09:03

Mohsin