Skip to content
Fix Code Error

Equivalent of shell ‘cd’ command to change the working directory?

March 13, 2021 by Code Error
Posted By: Peter

cd is the shell command to change the working directory.

How do I change the current working directory in Python?

Solution

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.

Answered By: sludge

Related Articles

  • Can't install via pip because of egg_info error
  • Jetpack Compose and Hilt Conflict
  • Gradle error: Execution failed for task…
  • Safe Area of Xcode 9
  • What's the difference between eval, exec, and compile?
  • Do you (really) write exception safe code?
  • Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)
  • org.gradle.api.tasks.TaskExecutionException:…
  • data.table vs dplyr: can one do something well the…
  • How to update Python?
  • How can I safely create a nested directory?
  • Problems with local variable scope. How to solve it?
  • Manually raising (throwing) an exception in Python
  • Flutter: RenderBox was not laid out
  • JS Graph recursive vs iterative DFS order difference
  • Install pip in docker
  • What is a NullReferenceException, and how do I fix it?
  • How to get $HOME directory of different user in bash script?
  • How do I merge two dictionaries in a single…
  • How to end C++ code
  • Using recursion in a Vue component with JSON
  • What is your most productive shortcut with Vim?
  • Ukkonen's suffix tree algorithm in plain English
  • How can I throw CHECKED exceptions from inside Java…
  • Why is "except: pass" a bad programming practice?
  • Remove Object from Array using JavaScript
  • Usage of __slots__?
  • How do i update a javascript variable as its value changes?
  • "OSError: [Errno 1] Operation not permitted" when…
  • ansible : how to pass multiple commands
  • How using try catch for exception handling is best practice
  • Best way to replace multiple characters in a string?
  • Logging best practices
  • Smart way to truncate long strings
  • Relative imports for the billionth time
  • How do I use 3DES encryption/decryption in Java?
  • Throw HttpResponseException or return…
  • Subprocess changing directory
  • java.sql.SQLException: - ORA-01000: maximum open…
  • Item position in RecyclerView only changing when…
  • How to prevent scrolling the whole page?
  • Reference - What does this regex mean?
  • Python File Error: unpack requires a buffer of 16 bytes
  • Node.js Best Practice Exception Handling
  • "Large data" workflows using pandas
  • How does is-invalid bootstrap class work?
  • What are type hints in Python 3.5?
  • Find current directory and file's directory
  • What does Ruby have that Python doesn't, and vice versa?
  • What is an IndexOutOfRangeException /…
  • Secure hash and salt for PHP passwords
  • Running shell command and capturing the output
  • Are dictionaries ordered in Python 3.6+?
  • How to permanently set $PATH on Linux/Unix?
  • File changed listener in Java
  • Java 8: Lambda-Streams, Filter by Method with Exception
  • "Keep Me Logged In" - the best approach
  • Keras Sequential API is replacing every layer with…
  • Proper use of the IDisposable interface
  • Adding Dynamic Input Fields With VueJs
  • What is the difference between venv, pyvenv, pyenv,…
  • Deleting folders in python recursively
  • What is the difference between bottom-up and top-down?
  • What are the undocumented features and limitations…
  • Catching multiple exception types in one catch block
  • What does "Fatal error: Unexpectedly found nil while…
  • How to efficiently use try...catch blocks in PHP
  • Simplest way to create Unix-like continuous pipeline…
  • Python: OSError: [Errno 2] No such file or directory: ''
  • How to determine the current shell I'm working on
  • Delay content of test of Cloud Functions with Mocha
  • How to test that no exception is thrown?
  • How to avoid a System.Runtime.InteropServices.COMException?
  • What version of Python is on my Mac?
  • JavaScript gives NaN error on the page but variable…
  • How do I return the response from an asynchronous call?
  • How to sleep a process when using multiprocessing in…
  • Pip not working in base conda environment
  • Catch an exception thrown by an async void method
  • How to find out the number of CPUs using python
  • The definitive guide to form-based website authentication
  • Fastest way to iterate over all the chars in a String
  • Assigning a variable NaN in python without numpy
  • OpenCV Object detection with Feature Detection and…
  • SQL Transaction Error: The current transaction…
  • How would I create a UIAlertView in Swift?
  • How does PHP 'foreach' actually work?
  • What is the correct way to setup CORS with ASP.NET…
  • Creating a singleton in Python
  • How to insert data in only one type of Vector in…
  • Exception thrown in catch and finally clause
  • Command prompt won't change directory to another drive
  • What is a plain English explanation of "Big O" notation?
  • Checkout another branch when there are uncommitted…
  • How to add fade animation for this tab
  • Why does C++ code for testing the Collatz conjecture…
  • Design DFA accepting binary strings divisible by a…
  • Can't upload files with Apollo-client GraphQL in…
  • mkdir -p functionality in Python
  • Vue.js + Vuex: How to mutate nested item state?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Running shell command and capturing the output

Next Post:

Finding the average of a list

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error