How do I change the working directory in Python?

前端 未结 14 1147
天涯浪人
天涯浪人 2020-11-22 01:59

cd is the shell command to change the working directory.

How do I change the current working directory in Python?

相关标签:
14条回答
  • 2020-11-22 02:11

    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.

    0 讨论(0)
  • 2020-11-22 02:17
    import os
    
    abs_path = 'C://a/b/c'
    rel_path = './folder'
    
    os.chdir(abs_path)
    os.chdir(rel_path)
    

    You can use both with os.chdir(abs_path) or os.chdir(rel_path), there's no need to call os.getcwd() to use a relative path.

    0 讨论(0)
  • 2020-11-22 02:17

    Further into direction pointed out by Brian and based on sh (1.0.8+)

    from sh import cd, ls
    
    cd('/tmp')
    print ls()
    
    0 讨论(0)
  • 2020-11-22 02:20

    The Path objects in path library offer both a context manager and a chdir method for this purpose:

    from path import Path
    
    with Path("somewhere"):
        ...
    
    Path("somewhere").chdir()
    
    0 讨论(0)
  • 2020-11-22 02:26

    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().

    More here

    0 讨论(0)
  • 2020-11-22 02:27

    If you use spyder and love GUI, you can simply click on the folder button on the upper right corner of your screen and navigate through folders/directories you want as current directory. After doing so you can go to the file explorer tab of the window in spyder IDE and you can see all the files/folders present there. to check your current working directory go to the console of spyder IDE and simply type

    pwd
    

    it will print the same path as you have selected before.

    0 讨论(0)
提交回复
热议问题