Hướng dẫn what is the command to change directory in python? - lệnh thay đổi thư mục trong python là gì?

Thay đổi thư mục hiện tại của quá trình tập lệnh là tầm thường. Tôi nghĩ rằng câu hỏi thực sự là làm thế nào để thay đổi thư mục hiện tại của cửa sổ lệnh mà từ đó tập lệnh Python được gọi, điều này rất khó. Một tập lệnh dơi trong Windows hoặc tập lệnh bash trong shell bash có thể thực hiện điều này với lệnh CD thông thường vì bản thân shell là trình thông dịch. Trong cả Windows và Linux Python là một chương trình và không có chương trình nào có thể thay đổi trực tiếp môi trường của cha mẹ. Tuy nhiên, sự kết hợp của một tập lệnh shell đơn giản với tập lệnh Python thực hiện hầu hết các công cụ cứng có thể đạt được kết quả mong muốn. Ví dụ: để tạo một lệnh CD mở rộng có lịch sử truyền tải để xem lại lùi/chuyển tiếp/chọn, tôi đã viết một tập lệnh Python tương đối phức tạp được gọi bởi một tập lệnh dơi đơn giản. Danh sách truyền tải được lưu trữ trong một tệp, với thư mục đích trên dòng đầu tiên. Khi tập lệnh Python trở lại, tập lệnh dơi đọc dòng đầu tiên của tệp và biến nó thành đối số với CD. Tập lệnh dơi hoàn chỉnh (trừ ý kiến ​​cho sự ngắn gọn) là:

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

Tập lệnh Python, DSUP.Py là:

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)

Xem thảo luận

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • Xem thảo luận

    Cải thiện bài viết

    Lưu bài viết

    Đọc in Python provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. 
    os.chdir() method in Python used to change the current working directory to specified path. It takes only a single argument as new directory path.
     

    Bàn luận os.chdir(path)
    Parameters: 
    path: A complete path of directory to be changed to new directory path.
    Returns: Doesn’t return any value

    Mã số 1: Sử dụng chdir () để thay đổi thư mục Use chdir() to change the directory

    Python3

    import os

    os.chdir(r"C:\Users\Gfg\Desktop\geeks")

    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)
    
    0
    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)
    
    1
    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)
    
    2)

    Output:    

    Directory changed

    Mã số 2: Sử dụng OS.GetCwd () & NBSP; Để biết thư mục làm việc hiện tại của tệp, phương thức getCwd () có thể được sử dụng. Sau khi thay đổi đường dẫn, người ta có thể xác minh đường dẫn của thư mục làm việc hiện tại bằng phương pháp này. & NBSP; Use of os.getcwd() 
    To know the current working directory of the file, getcwd() method can be used. After changing the path, one can verify the path of current working directory using this method. 

    Python3

    import os

    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)
    
    6
    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)
    
    7)

    Mã số 2: Sử dụng OS.GetCwd () & NBSP; Để biết thư mục làm việc hiện tại của tệp, phương thức getCwd () có thể được sử dụng. Sau khi thay đổi đường dẫn, người ta có thể xác minh đường dẫn của thư mục làm việc hiện tại bằng phương pháp này. & NBSP;

    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)
    
    0
    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)
    
    1
    Directory changed
    4
    Directory changed
    5

    Output:    

    Current working directory is: c:\\gfg_dir

    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)
    
    9
    Directory changed
    0
    Directory changed
    1
    Code #3: Handling the errors while changing the directory 

    Python3

    & nbsp; & nbsp; Mã số 3: Xử lý các lỗi trong khi thay đổi thư mục & nbsp;

    import

    Directory changed
    7

    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)
    
    9
    Directory changed
    0
    Directory changed
    1

    Current working directory is: c:\\gfg_dir
    4
    Current working directory is: c:\\gfg_dir
    5

    Current working directory is: c:\\gfg_dir
    6
    Current working directory is: c:\\gfg_dir
    7

    Current working directory is: c:\\gfg_dir
    6
    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)
    
    0
    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)
    
    1
    Inserting inside- c:\gfg_dir\gfg
    Something wrong with specified directory. Exception- 
    Restoring the path
    Current directory is- c:\gfg_dir\gfg
    1
    Inserting inside- c:\gfg_dir\gfg
    Something wrong with specified directory. Exception- 
    Restoring the path
    Current directory is- c:\gfg_dir\gfg
    2

    Inserting inside- c:\gfg_dir\gfg
    Something wrong with specified directory. Exception- 
    Restoring the path
    Current directory is- c:\gfg_dir\gfg
    3
    Current working directory is: c:\\gfg_dir
    5

    Current working directory is: c:\\gfg_dir
    6
    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)
    
    0
    Inserting inside- c:\gfg_dir\gfg
    Something wrong with specified directory. Exception- 
    Restoring the path
    Current directory is- c:\gfg_dir\gfg
    7

    Current working directory is: c:\\gfg_dir
    1
    Directory changed
    0
    Current working directory is: c:\\gfg_dir
    3

    import2

    Current working directory is: c:\\gfg_dir
    5

    Current working directory is: c:\\gfg_dir
    6
    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)
    
    0
    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)
    
    1import7)

    Current working directory is: c:\\gfg_dir
    6os0

    Current working directory is: c:\\gfg_dir
    6
    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)
    
    0
    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)
    
    1os4
    Inserting inside- c:\gfg_dir\gfg
    Something wrong with specified directory. Exception- 
    Restoring the path
    Current directory is- c:\gfg_dir\gfg
    2

    Output:  

    Inserting inside- c:\gfg_dir\gfg
    Something wrong with specified directory. Exception- 
    Restoring the path
    Current directory is- c:\gfg_dir\gfg

    Làm cách nào để thay đổi thư mục trong Python?

    Để thay đổi thư mục làm việc hiện tại trong Python, hãy sử dụng phương thức chdir ().Phương thức chấp nhận một đối số, đường dẫn đến thư mục mà bạn muốn thay đổi.Đối số đường dẫn có thể là tuyệt đối hoặc tương đối.use the chdir() method. The method accepts one argument, the path to the directory to which you want to change. The path argument can be absolute or relative.

    Làm cách nào để chuyển một tệp sang một thư mục khác trong Python?

    Di chuyển () Phương thức di chuyển các tệp trong Python bằng cách sử dụng.Shutil.Phương thức di chuyển () lấy hai đối số đầu tiên là đường dẫn nguồn hoàn chỉnh và hướng thứ hai là đường dẫn đích (bao gồm tên tệp/thư mục để di chuyển), hàm di chuyển sẽ chuyển tệp từ nguồn sang đích. move Files in Python using the. The shutil. move() method takes two arguments first one is the complete source path and the second one is the destination path (including the file/folder name to move), the move function will move the file from source to the destination.

    Làm thế nào để bạn đi đến một thư mục tập tin trong Python?

    Đường dẫn thư mục sử dụng một dấu gạch chéo về phía trước mà không đề cập đến hệ điều hành.Windows sử dụng dấu gạch chéo ngược để biểu thị các thư mục con, trong khi Linux sử dụng dấu gạch chéo phía trước.Nhưng trong Python, các dấu gạch chéo về phía trước luôn hoạt động, ngay cả trên Windows.forward slashes always work, even on Windows.