4

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. 
itsmrbeltre
  • 412
  • 7
  • 18
Felix
  • 83
  • 1
  • 8

2 Answers2

6

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.

heemayl
  • 39,294
  • 7
  • 70
  • 76
  • While correct for what you've shown, I'm confused if the OP even wants the home directory rather than just another directory and `~` was an example. – pstatix Feb 22 '18 at 18:54
1

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"))
Mohsin
  • 536
  • 6
  • 18