0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[python] カレントディレクトリの移動

Posted at

やりたいこと

  • カレントディレクトリの取得
  • カレントディレクトリの移動

ディレクトリ構造

サンプルのディレクトリはこんな感じ

Sample
└ Input
├ Output
└ PY
  ├ sample.py
  └ sql
   └ aaa.sql

ライブラリ

  • カレントディレクトリの取得 os.getcwd()
  • カレントディレクトリを移動  os.chdir()

やってみる

Sample\PYsample.pyが実行ファイルとしてやってみる
よって、カレントディレクトリはSample\PYでスタート

カレントディレクトリを取得する

os.getcwd()を使う

# カレントディレクトリ
print(os.getcwd())
結果
c:\Users\Sample\PY

カレントディレクトリの直下のディレクトリを取得する

# カレントディレクトリの直下のディレクトリ
print(os.path.join(os.getcwd(),'sql'))

# カレントディレクトリ
print(os.getcwd())
結果
c:\Users\Sample\PY\sql
c:\Users\Sample\PY

直下のディレクトリとはos.path.joinつないであげる
ディレクトリを移動したわけではないので、 1階層下を取得してもカレントディレクトリは変わらない

カレントディレクトリを移動する

os.chdir()を使って移動
上の階層は..を使う

# カレントディレクトリ
print(os.getcwd())

# 上の階層に移動
os.chdir('../Output')

# カレントディレクトリ
print(os.getcwd())
結果
c:\Users\Sample\PY
c:\Users\Sample\Output
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?