Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to specify the previous directory python?

I am attempting to make a Python testing script module self-contained directory-wise for scalability and maintainability purposes.

I have done some research and haven't been able to find the answer i'm looking for. Basically, I would like to determine if there is a function in Python that can do something similar to cd - in shell.

I would generally like to avoid typing in full path-names, and have all the paths relative to a specified environment.

Example: I have my main directory where my scripts are located python-scripts, I have folders for each testing environment demo, and a screenshot folder for each testing environment demo-screenshots.

If i wanted to save a screenshot to the screenshot with Python, while working in the demo directory, I would just send it to the directory below: demo-screenshots, using the path '/demo-screenshots/example.png'. The problem is that I don't understand how to move back a directory.

Thank you.

like image 278
kplus Avatar asked Jan 22 '13 16:01

kplus


People also ask

How do you specify a directory in Python?

The directory path uses a forward slash without mentioning operating system. Windows uses backward slashes to denote subdirectories, while Linux use forward slashes. But in Python, forward slashes always work, even on Windows.

How do I change the run directory in Python?

To change the current working directory in Python, use the chdir() method. The method accepts one argument, the path to the directory to which you want to change. The path argument can be absolute or relative.


1 Answers

You're looking to change the working directory? The OS module in python has a lot of functions to help with this.

import os
os.chdir( path )

path being ".." to go up one directory. If you need to check where you are before/after a change of directory you can issue the getcwd() command:

mycwd = os.getcwd()
os.chdir("..")
#do stuff in parent directory
os.chdir(mycwd)     # go back where you came from
like image 50
Mike Avatar answered Oct 22 '22 14:10

Mike