Hướng dẫn python terminal change directory

Changing the current directory of the script process is trivial. I think the question is actually how to change the current directory of the command window from which a python script is invoked, which is very difficult. A Bat script in Windows or a Bash script in a Bash shell can do this with an ordinary cd command because the shell itself is the interpreter. In both Windows and Linux Python is a program and no program can directly change its parent's environment. However the combination of a simple shell script with a Python script doing most of the hard stuff can achieve the desired result. For example, to make an extended cd command with traversal history for backward/forward/select revisit, I wrote a relatively complex Python script invoked by a simple bat script. The traversal list is stored in a file, with the target directory on the first line. When the python script returns, the bat script reads the first line of the file and makes it the argument to cd. The complete bat script (minus comments for brevity) is:

Nội dung chính

  • Getting the current working directory- os.getcwd()
  • Change the current working directory: os.chdir()
  • How do I change the directory of a file in Python?
  • Which method is used to change the directory in Python?
  • How do you move to a different folder in Python?

if _%1 == _. goto cdDone
if _%1 == _? goto help
if /i _%1 NEQ _-H goto doCd
:help
echo d.bat and dSup.py 2016.03.05. Extended chdir.
echo -C = clear traversal list.
echo -B or nothing = backward (to previous dir).
echo -F or - = forward (to next dir).
echo -R = remove current from list and return to previous.
echo -S = select from list.
echo -H, -h, ? = help.
echo . = make window title current directory.
echo Anything else = target directory.
goto done

:doCd
%~dp0dSup.py %1
for /F %%d in ( %~dp0dSupList ) do (
    cd %%d
    if errorlevel 1 ( %~dp0dSup.py -R )
    goto cdDone
)
:cdDone
title %CD%
:done

The python script, dSup.py is:

import sys, os, msvcrt

def indexNoCase ( slist, s ) :
    for idx in range( len( slist )) :
        if slist[idx].upper() == s.upper() :
            return idx
    raise ValueError

# .........main process ...................
if len( sys.argv ) < 2 :
    cmd = 1 # No argument defaults to -B, the most common operation
elif sys.argv[1][0] == '-':
    if len(sys.argv[1]) == 1 :
        cmd = 2 # '-' alone defaults to -F, second most common operation.
    else :
        cmd = 'CBFRS'.find( sys.argv[1][1:2].upper())
else :
    cmd = -1
    dir = os.path.abspath( sys.argv[1] ) + '\n'

# cmd is -1 = path, 0 = C, 1 = B, 2 = F, 3 = R, 4 = S

fo = open( os.path.dirname( sys.argv[0] ) + '\\dSupList', mode = 'a+t' )
fo.seek( 0 )
dlist = fo.readlines( -1 )
if len( dlist ) == 0 :
    dlist.append( os.getcwd() + '\n' ) # Prime new directory list with current.

if cmd == 1 : # B: move backward, i.e. to previous
    target = dlist.pop(0)
    dlist.append( target )
elif cmd == 2 : # F: move forward, i.e. to next
    target = dlist.pop( len( dlist ) - 1 )
    dlist.insert( 0, target )
elif cmd == 3 : # R: remove current from list. This forces cd to previous, a
                # desireable side-effect
    dlist.pop( 0 )
elif cmd == 4 : # S: select from list
# The current directory (dlist[0]) is included essentially as ESC.
    for idx in range( len( dlist )) :
        print( '(' + str( idx ) + ')', dlist[ idx ][:-1])
    while True :
        inp = msvcrt.getche()
        if inp.isdigit() :
            inp = int( inp )
            if inp < len( dlist ) :
                print( '' ) # Print the newline we didn't get from getche.
                break
        print( ' is out of range' )
# Select 0 means the current directory and the list is not changed. Otherwise
# the selected directory is moved to the top of the list. This can be done by
# either rotating the whole list until the selection is at the head or pop it
# and insert it to 0. It isn't obvious which would be better for the user but
# since pop-insert is simpler, it is used.
    if inp > 0 :
        dlist.insert( 0, dlist.pop( inp ))

elif cmd == -1 : # -1: dir is the requested new directory.
# If it is already in the list then remove it before inserting it at the head.
# This takes care of both the common case of it having been recently visited
# and the less common case of user mistakenly requesting current, in which
# case it is already at the head. Deleting and putting it back is a trivial
# inefficiency.
    try:
        dlist.pop( indexNoCase( dlist, dir ))
    except ValueError :
        pass
    dlist = dlist[:9] # Control list length by removing older dirs (should be
                      # no more than one).
    dlist.insert( 0, dir ) 

fo.truncate( 0 )
if cmd != 0 : # C: clear the list
    fo.writelines( dlist )

fo.close()
exit(0)

A portable method of interacting with the operating system is offered through the OS Python Module. The module, which is a part of the default Python library, contains tools for locating and modifying the working directory.

The following contents are described in this article.

  • How to obtain the current working directory os.getcwd()
  • Changing the current working directory : os.chdir()

The __file__ function returns the path to the current script file (.py).

Getting the current working directory- os.getcwd()

The function os.getcwd() returns as a string str the absolute path to Python's current working directory. "Get current working directory" (getcwd) refers to the ability to print the current working directory with an operating system using print() and getcwd ().

The trailing slash character is omitted from the string that is returned.

Example

Following is an example to get the current working directory:

import os cwd = os.getcwd() print("Th Current working directory is: {0}".format(cwd)) print("os.getcwd() returns an object of type: {0}".format(type(cwd)))

Output

Following is an output of the above code:

The Current working directory is: C:\Users\Lenovo\Desktopos.getcwd() returns an object of type: ⁢class 'str'>
os.getcwd() returns an object of type: 

Change the current working directory: os.chdir()

Use the chdir() function in Python to change the current working directory.

The path to the directory you wish to change to is the only parameter the method allows. You can use either an absolute or relative path argument.

Example

Following is an example to change the current working directory:

import os print("The Current working directory is: {0}".format(os.getcwd())) os.chdir('C:\Users\Lenovo\Downloads\Works\') print("The Current working directory now is: {0}".format(os.getcwd()))

Output

Following is an output of the above code:

The Current working directory is: C:\Users\Lenovo\Desktop
The Current working directory now is: C:\Users\Lenovo\Downloads\Works

Note − A NotADirectoryError exception is thrown if a directory is not provided as an argument to the chdir() method. There is a FileNotFoundError exception raised if the provided directory is not found. A PermissionError exception is raised if the user running the script doesn't have the required permissions.

Example

import os path = 'C:\Users\Lenovo\Downloads\Works\' try: os.chdir(path) print("The Current working directory is: {0}".format(os.getcwd())) except FileNotFoundError: print("Directory: {0} does not exist".format(path)) except NotADirectoryError: print("{0} is not a directory".format(path)) except PermissionError: print("No permissions to change to {0}".format(path))

Output

Following is an output of the above example:

The Current working directory is: C:\Users\Lenovo\Downloads\Works

Hướng dẫn python terminal change directory

Updated on 17-Aug-2022 13:05:49

  • Related Questions & Answers
  • How to know current working directory in Python?
  • How to change current directory using Python?
  • How to change the shell working directory in Linux?
  • How to change the root directory of the current process in Python?
  • How to set the current working directory in Python?
  • How to know the current position within a file in Python?
  • How to find current directory of program execution in Python?
  • How to change the permission of a directory using Python?
  • How to change the owner of a directory using Python?
  • How to clear Python shell?
  • How to print full path of current file's directory in Python?
  • How to get full path of current file's directory in Python?
  • How to print current package cache directory information in android?
  • How to get the current username and directory in Golang?
  • Java Program to Get Current Working Directory

How do I change the directory of a file in Python?

Set File Path in Python.

Use the \ Character to Specify the File Path in Python..

Use the Raw String Literals to Specify the File Path in Python..

Use the os.path() Function to Specify the File Path in Python..

Use the pathlib.Path() Function to Specify the File Path in Python..

Which method is used to change the directory in Python?

chdir() method in Python used to change the current working directory to specified path.

How do you move to a different folder in Python?

Steps to Move a File in Python.

Find the path of a file. We can move a file using both relative path and absolute path. ... .

Use the shutil.move() function. The shutil. ... .

Use the os.listdir() and shutil move() function to move all files. Suppose you want to move all/multiple files from one directory to another, then use the os..