Python Scrypt to step back a directory

44231
3
09-14-2011 02:08 PM
philiptivel
Emerging Contributor
I would like to step back a directory in python without having to prompt the user to do it in my script. For example the user selects a dataset here C:\Projects\test\database.mdb\dataset to run a process on. I then want the database that the dataset is in to be compacted without prompting the user for the database as well. Basically I want to know what the python version of cd.. is
Tags (2)
0 Kudos
3 Replies
MarcNakleh
Regular Contributor
Hi there,

There are a couple of ways to do this, though Python's built-in way would be:
os.path.dirname(path_to_dataset)

import os
pathX = r'C:/Hello/HelloWorld'
print os.path.dirname(pathX)

Result: C:/Hello

which returns the parent directory of the file or folder under consideration. So, if you feed it a file, it will give the directory the file is in. If you give it a folder, it will return the folder hosting it.
0 Kudos
philiptivel
Emerging Contributor
That worked great, thanks!
0 Kudos
RDHarles
Regular Contributor
You can also do what you were suggesting in your original post (change directories "back one") by using os.chdir():

import os
print "Current: "+os.getcwd()
>> C:/jobs/Alpine
os.chdir('..')
print "Back one dir: "+os.getcwd()
>> C:/jobs
0 Kudos