0

I have encountered something, I am building a command line tool in python. Now I use the os.chdir to change the current working directory (with command cd). I noticed that when I put .. in the input, it brings me back in the directory tree. For example, I am in directory D:\pythonProject I input cd .. So the chdir parameter is D:\pythonProject\.. (I am using os.path.join). And then, the current working directory becomes D:. Obviously I can't go back more than that. But why does this happen? I didn't include handling for .. in my code. Is it something that is built-in?

This is my function:

def change_working_dir(path):
    path_dest = os.path.join(os.getcwd(), path)
    if os.path.exists(path_dest):
        if os.path.isdir(path_dest):
            os.chdir(path_dest)
        elif os.path.isfile(path_dest):
            os.startfile(path_dest)
        else:
            print("No such path.")

Thanks!

nat34
  • 3
  • 5
  • yes '..' is the built-in for the parent directory. if you try in your terminal, cd .. does the same – MrE Oct 18 '22 at 18:24
  • even if its in the end of a path yeah? so for example, ".." and "C:\python\.." would do the same of going back to "C:\"? – nat34 Oct 18 '22 at 18:29
  • Just as a small correction/clarification, nat34. There is no directory ```D:```; that is only a drive with an identifying letter allocated. The root directory of a drive is ```\```, so the directory would be ```D:\```, _(i.e. the root directory of drive ```D:```)_. – Compo Oct 19 '22 at 17:04

0 Answers0