cd in a function
- getcwd
- chdir
In this example we have a function in which we change to a directory and then when we are done we change back to the original directory.
For this to work first we save the current working directory using the os.getcwd
call. Unfortunatelly in the middle of the code there
is a conditional call to return
. If that condition is True
we won't change back to the original directory. We could fix this by
calling os.chdir(start_dir)
just before calling return
. However this would still not solve the problem if there is an exception
in the function.
import sys
import os
def do_something(path):
start_dir = os.getcwd()
os.chdir(path)
content = os.listdir()
number = len(content)
print(number)
if number < 15:
return
os.chdir(start_dir)
def main():
if len(sys.argv) != 2:
exit(f"Usage: {sys.argv[0]} PATH")
path = sys.argv[1]
print(os.getcwd())
do_something(path)
print(os.getcwd())
main()
$ python no_context_cd.py /tmp/
/home/gabor/work/slides/python-programming/examples/advanced
19
/home/gabor/work/slides/python-programming/examples/advanced
$ python no_context_cd.py /opt/
/home/gabor/work/slides/python-programming/examples/advanced
9
/opt
- In the second example
return
was called and thus we stayed on the /opt directory.:w