Python 作業ディレクトリ変更方法:os.chdir()徹底解説
osモジュールのchdir()関数を使用して、現在の作業ディレクトリを設定することができます。
import os
# 获取当前工作路径
current_path = os.getcwd()
print("当前工作路径:", current_path)
# 设置新的工作路径
new_path = "/path/to/new/directory"
os.chdir(new_path)
# 检查新的工作路径
current_path = os.getcwd()
print("新的工作路径:", current_path)
上記の例では、まずos.getcwd()関数を使って現在の作業ディレクトリを取得し、次にos.chdir()関数を使って新しい作業ディレクトリを設定します。最後に再びos.getcwd()関数を使って設定が成功したかどうかを確認します。