How can I change directory or cd in Python

+2 votes
Unable to change the current working directory in Python. How do i change it?
Apr 14, 2018 in Python by 93.lynn
• 1,610 points

6 answers to this question.

+1 vote

Just import the "os" module and enter the path you want it to get changed.

import os


Hope it works!!

If you are a beginner and need to know more about Python, It's recommended to go for Python Certification course today.


answered Apr 14, 2018 by anto.trigg4
• 3,440 points
+1 vote

If You would like to perform something like "cd.." option, just type:


it is the same as in Windows cmd: cd.. Of course import os is neccessary (e.g type it as 1st line of your code)

answered Oct 18, 2018 by Neha Kerketta
+1 vote

os.chdir() is the right way.

answered Oct 18, 2018 by Sillan Witt
+1 vote

cd() is easy to write using a generator and a decorator.

from contextlib import contextmanager
import os

def cd(newdir):
    prevdir = os.getcwd()
answered Oct 18, 2018 by Kalgie Mathew
+1 vote

I would use os.chdir like this:


By the way, if you need to figure out your current path, use os.getcwd().

answered Oct 18, 2018 by abc
+1 vote
Context Manager: cd
import os

class cd:
    """Context manager for changing the current working directory"""
    def __init__(self, newPath):
        self.newPath = os.path.expanduser(newPath)

    def __enter__(self):
        self.savedPath = os.getcwd()

    def __exit__(self, etype, value, traceback):
answered Oct 18, 2018 by Nabarupa

Related Questions In Python

0 votes
2 answers

How can I rename multiple files in a certain directory using Python?

import os from optparse import OptionParser, Option class MyOption ...READ MORE

answered Jul 29, 2020 in Python by The real slim shady
0 votes
1 answer

How can I prevent or alter access to class variables in Python?

The ActiveState solution that Pynt references makes instances of ...READ MORE

answered Dec 5, 2018 in Python by aryya
• 7,440 points
0 votes
1 answer

How can I change the data type to string in Python?

You can use str(variablename) This is called conversion ...READ MORE

answered Dec 18, 2018 in Python by Shuvodip
0 votes
1 answer

How can I make use of getopt or optarg in Python?

Hi, I was asked this by one ...READ MORE

answered Feb 8, 2019 in Python by Nymeria
• 3,520 points
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,405 views
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,440 points
+4 votes
7 answers