Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of shell 'cd' command to change the working directory?

Tags:

python

cd

cd is the shell command to change the working directory.

How do I change the current working directory in Python?

like image 360
too much php Avatar asked Jan 10 '09 20:01

too much php


People also ask

Which shell command is used to change current working directory?

The cd command used to change the current working directory in the Linux/Unix operating system. In the Windows operating system for the same purpose the cd or chdir command available. The cd command also available in the EFI shell (Extensible Firmware Shell).

How do you change directory in shell?

To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.

How do I change my current working directory?

To change the current working directory(CWD) os. chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.


1 Answers

You can change the working directory with:

import os  os.chdir(path) 

There are two best practices to follow when using this method:

  1. Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.
  2. Return to your old directory when you're done. This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in his answer.

Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process.

like image 184
Michael Labbé Avatar answered Oct 06 '22 14:10

Michael Labbé