OSモジュール Python では、オペレーティング システムと対話するための関数が提供されます。 OS は、Python の標準ユーティリティ モジュールに含まれます。このモジュールは、オペレーティング システムに依存する機能を使用するポータブルな方法を提供します。
os.chdir() 現在の作業ディレクトリを指定されたパスに変更するために使用される Python のメソッド。新しいディレクトリ パスとして引数を 1 つだけ取ります。
構文: os.chdir(パス)
パラメーター:
パス: 新しいディレクトリ パスに変更されるディレクトリの完全なパス。
戻り値: 値を返さない
コード #1: chdir()を使用してディレクトリを変更します
Python3
Javaチェックがnullです
# Python3 program to change the> # directory of file using os.chdir() method> # import os library> import> os> # change the current directory> # to specified directory> os.chdir(r> 'C:UsersGfgDesktopgeeks'> )> print> (> 'Directory changed'> )> |
>
>
出力:
Directory changed>
コード #2: os.getcwd() の使用
ファイルの現在の作業ディレクトリを知るには、getcwd() メソッドを使用できます。パスを変更した後、この方法を使用して現在の作業ディレクトリのパスを確認できます。
Python3
# import os module> import> os> # change the current working directory> # to specified path> os.chdir(> 'c:gfg_dir'> )> # verify the path using getcwd()> cwd> => os.getcwd()> # print the current directory> print> (> 'Current working directory is:'> , cwd)> |
>
df.loc
>
出力:
Current working directory is: c:gfg_dir>
コード #3: ディレクトリ変更時のエラーの処理
Python3
# 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> :> > os.chdir(fd)> > print> (> 'Inserting inside-'> , os.getcwd())> > # Caching the exception> except> :> > print> ('Something wrong with specified> > directory. Exception> -> ', sys.exc_info())> > # handling with finally> finally> :> > print> (> 'Restoring the path'> )> > os.chdir(cwd)> > print> (> 'Current directory is-'> , os.getcwd())> |
>
>
出力:
Inserting inside- c:gfg_dirgfg Something wrong with specified directory. Exception- Restoring the path Current directory is- c:gfg_dirgfg>