Как мне изменить каталог (CD) в Python? - PullRequest
598 голосов
/ 10 января 2009

cd как в команде оболочки для изменения рабочего каталога.

Как изменить текущий рабочий каталог в Python?

Ответы [ 14 ]

2 голосов
/ 07 ноября 2018
import os

abs_path = 'C://a/b/c'
rel_path = './folder'

os.chdir(abs_path)
os.chdir(rel_path)

Вы можете использовать оба с os.chdir (abs_path) или os.chdir (rel_path), нет необходимости вызывать os.getcwd () для использования относительного пути.

1 голос
/ 14 сентября 2018
#import package
import os

#change directory
os.chdir('my_path')

#get location 
os.getcwd()

Также хорошо проверить все другие полезные команды в пакете ОС здесь https://docs.python.org/3/library/os.html

0 голосов
/ 07 марта 2016

Изменение текущей директории процесса скрипта тривиально. Я думаю, что на самом деле вопрос заключается в том, как изменить текущий каталог командного окна, из которого вызывается скрипт Python, что очень сложно. Сценарий Bat в Windows или сценарий Bash в оболочке Bash могут сделать это с помощью обычной команды cd, поскольку сама оболочка является интерпретатором. И в Windows, и в Linux Python - это программа, и ни одна из программ не может напрямую изменить среду своего родителя. Однако сочетание простого сценария оболочки с сценарием Python, выполняющего большинство сложных задач, может достичь желаемого результата. Например, чтобы создать расширенную команду cd с историей обхода для пересмотра назад / вперед / выбора, я написал относительно сложный скрипт Python, вызываемый простым скриптом bat. Список прохождения хранится в файле с целевым каталогом в первой строке. Когда скрипт python возвращается, скрипт bat читает первую строку файла и делает его аргументом для cd. Полный скрипт летучей мыши (за исключением краткости комментариев):

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

Сценарий python, dSup.py:

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 голосов
/ 11 января 2009

и для простого интерактивного использования ipython имеет все встроенные команды оболочки.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...