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 13, 2018 in Python by 93.lynn
• 1,550 points
77 views

6 answers to this question.

+1 vote

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

import os

os.chdir(path)
answered Apr 13, 2018 by anto.trigg4
• 3,420 points
+1 vote

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

os.chdir("..")

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

@contextmanager
def cd(newdir):
    prevdir = os.getcwd()
    os.chdir(os.path.expanduser(newdir))
    try:
        yield
    finally:
        os.chdir(prevdir)
answered Oct 18, 2018 by Kalgie Mathew
+1 vote

I would use os.chdir like this:

os.chdir("/path/to/change/to")

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()
        os.chdir(self.newPath)

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

Related Questions In Python

0 votes
1 answer

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

Use os.rename(src, dst) to rename or move a file ...READ MORE

answered Nov 23, 2018 in Python by ariaholic
• 7,320 points
92 views
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 ariaholic
• 7,320 points
54 views
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 17, 2018 in Python by Shuvodip
44 views
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 in Python by Nymeria
• 3,500 points
33 views
+4 votes
6 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 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 135 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,420 points
70 views
+4 votes
7 answers