Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (33.1k points)

‘cd’ as in the shell command to change the working directory.

 How do I change the current working directory in Python?

1 Answer

0 votes
by (106k points)
edited by

In Python the working directory can be changed by following way:-

import os 

os.chdir(path)

When the current working directory in a subprocess changed it does not change the current working directory in the parent process. 

Another way it can be done by using contextmanager:-

contextmanager:-

Context managers in Python facilitate the proper handling of resources like file operations or database connections.

import os 

from contextlib import contextmanager 

@contextmanager 

def working_directory(directory):

    owd = os.getcwd()

    try: 

       os.chdir(directory)

       yield directory

    finally:

       os.chdir(owd)

To know more about this you can have a look at the following video tutorial:-

Be a Python Expert. Enroll in Python Programming Course by Intellipaat!

Related questions

0 votes
1 answer
asked Oct 3, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
+1 vote
1 answer

Browse Categories

...