Is it possible to specify the previous python directory?

I am trying to make the Python module for testing a script stand-alone in a directory for scalability and ease of maintenance.

I did some research and could not 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 the shell.

I would usually like not to enter full path names and have all the paths relative to the given environment.

Example: I have my main directory where my scripts are located python-scripts, I have folders for each test environment demoand a folder from the screen for each test environment demo-screenshots.

If I wanted to save a screenshot to a screenshot from Python while working in a directory demo, I just send it to the directory below: demo-screenshotsusing the path '/demo-screenshots/example.png'. The problem is that I do not understand how to move the directory.

Thank.

+5
source share
2 answers

Do you want to change the working directory? The python OS module has many features to help with this.

import os
os.chdir( path )

pathis ".."to go to one directory. If you need to check where you are before / after changing the directory, you can send the command getcwd():

mycwd = os.getcwd()
os.chdir("..")
#do stuff in parent directory
os.chdir(mycwd)     # go back where you came from
0
source
path = os.path.dirname(__file__)
print(path)

will output a CWD file, say C: \ Users \ Test \ Documents \ CodeRevamp \ Joke

path2 = os.path.dirname(path)
print(path2)

will print the parent directory of the file: C: \ Users \ Test \ Documents \ CodeRevamp

0
source

All Articles