0

I am using this code to get into the directory in Python:

os.chdir(path)

Then, I want to exit this directory to the last directory. What do I have to do? Thanks

Dipak Telangre
  • 1,792
  • 4
  • 19
  • 46
  • 2
    Does this answer your question? [Is it possible to specify the previous directory python?](https://stackoverflow.com/questions/14462833/is-it-possible-to-specify-the-previous-directory-python) –  Aug 09 '21 at 03:31

2 Answers2

1

I understood your problem , this may help.

import os

curr = os.getcwd() # this returns current working directory in which this code              #is.store it in curr variable

os.chdir('../') # this will change working directory to specified path.

os.chdir(curr) #now if you wnat to go back to your directory use this
atline
  • 28,355
  • 16
  • 77
  • 113
madhav
  • 11
  • 1
1

Yes. You can run the code os.getcwd() before the given line and store into a variable. and cd into this after.

import os
# ...
originalPath = os.getcwd()
os.chdir(path)
# process your task
os.chdir(originalPath)

Comment if this helps.

Hari Kishore
  • 2,201
  • 2
  • 19
  • 28