How to change directory with Subprocess in Python?

Sometimes, we want to change directory with Subprocess in Python.

In this article, we’ll look at how to change directory with Subprocess in Python.

How to change directory with Subprocess in Python?

To change directory with Subprocess in Python, we use the os.chdir method.

For instance, we write

import os

wd = os.getcwd()
os.chdir("/")
subprocess.Popen("ls")
os.chdir(wd)

to call os.chir to change the directory to /.

Then we call Popen with 'ls' to run the ls command on /.

Then we go back to the current working directory with

os.chdir(wd)

where wd is the current working directory path that we get with getcwd.

Conclusion

To change directory with Subprocess in Python, we use the os.chdir method.