0 votes
1 view
in Python by (33.2k 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 (107k 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:-

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 3, 2019 in Python by Sammy (47.8k points)
+1 vote
1 answer
asked May 18, 2019 in Python by Nigam (4.1k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...