[Python] Pitfalls: Be Careful with os.chdir

时间:2024-10-31 20:05:56

One thing you need to keep in mind is that when using os.chdir to change the working directory of current programme (script), make sure if we need to come back to the current working directory again.

Using os.chdir to change the current working directory anywhere in the programme will effect permanently, regardless if you are using it in a function or not, see the following example:

 import os

 def chdir_in_func():
print "Before chaning, in func"
print os.getcwd()
os.chdir("/home/")
print "After chaning, in func"
print os.getcwd() if __name__ == "__main__":
print "Before changing, outside func"
print os.getcwd()
chdir_in_func()
print "After changing, outside func"
print os.getcwd()

The output of this script will be:

Before changing, outside func
/home/chdir_in_func
Before chaning, in func
/home/chdir_in_func
After chaning, in func
/home
After changing, outside func
/home

We can see that in the function, if we changes the directory, the current working directory is changed too.

A suggested good practice to avoid such unconsciously mistake is that alway change back to your original working directory after the actions done in the new directory, unless you know you need to stay there for next operations. I would strongly recommend that in functions, if you have to change directory, always changes it back before returning:

def func():
cwd_save = os.getcwd()
os.chdir(new_dir)
# Actions in new_dir
os.chdir(cwd_save)
return True