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.
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.
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With