Sam Brown Sam Brown - 3 months ago 10
Python Question

How do go into a directory without being given its full path in python 2?

I am currently trying to go into a folder and call a python 2 script, but I cannot get any answer to go into a folder without using its full path. As example in DOS I would normally type this:

C:\unknownpath\> cd otherpath

Thanks for any help.


Try this:

import os

This at least matches your DOS example, and will change your working directory to otherpath relative to the directory the command is run from. For example if you are in /home/myusername/, then this will take you to /home/myusername/otherpath/. You can also use . for the current directory or .. to move back one directory. So if you are in /home/myusername/Desktop/, os.chdir('..') would change the working directory to /home/myusername/ and os.chdir('../Documents/ would change you to /home/myusername/Documents/, etc.

Forgive my use of Unix-style paths, but you should be able to easily translate these commands to Windows paths if that is the platform you are on. I don't want to attempt to use Windows paths in my examples because I won't be able to test their efficacy.