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
2,0134 gold badges25 silver badges49 bronze badges
-
2Does this answer your question? Is it possible to specify the previous directory python?user15801675– user158016752021年08月09日 03:31:39 +00:00Commented Aug 9, 2021 at 3:31
2 Answers 2
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.
answered Aug 9, 2021 at 3:40
Hari Kishore
2,9903 gold badges27 silver badges33 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Huy Vu Quang
When I run your code, I received this error: AttributeError: module 'os' has no attribute 'cwd'
Hari Kishore
it should be
os.getcwd(). ThanksI 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
32.1k19 gold badges102 silver badges134 bronze badges
Comments
lang-py