Pythonで現在の作業ディレクトリを変更する

OSモジュール Python では、オペレーティング システムと対話するために使用されます。このモジュールは Python の標準ユーティリティ モジュールに含まれるため、外部にインストールする必要はありません。ファイル名とパスが無効またはアクセスできない場合、または正しい型を持つがオペレーティング システムで受け入れられないその他の引数の場合、OS モジュールのすべての関数は OSError を発生させます。
変更するには 現在の作業ディレクトリ(CWD) os.chdir()メソッドが使用されます。このメソッドは、CWD を指定されたパスに変更します。新しいディレクトリ パスとして引数を 1 つだけ取ります。
注記: 現在の作業ディレクトリは、Python スクリプトが動作しているフォルダーです。

構文: os.chdir(パス)
パラメーター:
パス: 新しいディレクトリ パスに変更されるディレクトリの完全なパス。
戻り値: 値を返さない

例 #1: まずスクリプトの現在の作業ディレクトリを取得し、それからそれを変更します。以下は実装です。

Python3




# Python program to change the> # current working directory> import> os> # Function to Get the current> # working directory> def> current_path():> > print> (> 'Current working directory before'> )> > print> (os.getcwd())> > print> ()> # Driver's code> # Printing CWD before> current_path()> # Changing the CWD> os.chdir(> '../'> )> # Printing CWD after> current_path()>

出力:

Current working directory before C:UsersNikhil AggarwalDesktopgfg Current working directory after C:UsersNikhil AggarwalDesktop 

例2: ディレクトリ変更時のエラーの処理。

Python3




# Python program to change the> # current working directory> # importing all necessary libraries> import> sys, os> > # initial directory> cwd> => os.getcwd()> > # some non existing directory> fd> => 'false_dir/temp'> > # trying to insert to false directory> try> :> > print> (> 'Inserting inside-'> , os.getcwd())> > os.chdir(fd)> > # Caching the exception> except> :> > print> (> 'Something wrong with specified directory. Exception- '> )> > print> (sys.exc_info())> > # handling with finally> finally> :> > print> ()> > print> (> 'Restoring the path'> )> > os.chdir(cwd)> > print> (> 'Current directory is-'> , os.getcwd())>

出力:

C:UsersNikhil AggarwalDesktopgfg 内に挿入します
指定されたディレクトリに問題があります。例外-
(, FileNotFoundError(2, 'システムは指定されたパスを見つけることができません'), )
パスを復元する
現在のディレクトリは C:UsersNikhil AggarwalDesktopgfg です。