Pythonでディレクトリを操作する方法について解説します。
初心者にもわかりやすく、サンプルプログラムを使った解説を行います。
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi2_nayamu.png)
ディレクトリの操作って、どうすればいいんですか?
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi1_normal.png)
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi1_normal.png)
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi1_normal.png)
Pythonでディレクトリを操作する方法は、osモジュールを使用するのが一般的です。ファイルの作成や削除、移動、コピーなどができます。
目次
ディレクトリの作成
ディレクトリを作成するには、osモジュールのmkdir関数を使います。
import os
os.mkdir("new_directory")
ディレクトリの削除
ディレクトリを削除するには、osモジュールのrmdir関数を使います。
import os
os.rmdir("new_directory")
ディレクトリの移動
カレントディレクトリを変更するには、osモジュールのchdir関数を使います。
import os
os.chdir("new_directory")
絶対パスの取得
相対パスを絶対パスに変換するには、osモジュールのpath.abs.path関数を使います。
import os
absolute_path = os.path.abspath("new_directory")
print(absolute_path)
相対パスの取得
絶対パスを相対パスに変換するには、osモジュールのpath.relpath関数を使います。
import os
relative_path = os.path.relpath("/Users/username/new_directory")
print(relative_path)
パスの全ての要素を分解する
パスを分解して、ディレクトリ名とファイル名に分けるには、osモジュールのpath.split関数を使います。
import os
path = "/Users/username/new_directory"
dir_name, file_name = os.path.split(path)
print("Directory name:", dir_name)
print("File name:", file_name)
フォルダの内容を調べる
ディレクトリ内のファイルやフォルダの一覧を取得するには、osモジュールのlistdir関数を使います。
import os
folder_contents = os.listdir("new_directory")
print(folder_contents)
パスが正しいか調べる
パスが存在するかどうかを確認するには、osモジュールのpath.exists関数を使います。
import os
path = "/Users/username/new_directory"
if os.path.exists(path):
print("The path exists.")
else:
print("The path does not exist.")
まとめ
Pythonでディレクトリを操作する方法について解説しました。
- Pythonでは、osモジュールを使ってディレクトリの作成、削除、移動、コピーなどができます。
- osモジュールのpath関数を使って、絶対パスや相対パスを取得できます。
- フォルダの内容を調べるには、osモジュールのlistdir関数を使用します。
- パスの存在確認には、path.exists関数を使用します。
- パスを操作する際には、スラッシュ(/)かバックスラッシュ()を使うことができます。
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi2_normal.png)
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi2_normal.png)
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi2_normal.png)
Pythonでディレクトリを操作する方法がわかりました!
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi1_normal.png)
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi1_normal.png)
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi1_normal.png)
ディレクトリの操作は、プログラムを作る上で欠かせない機能の一つです。Pythonのosモジュールを使えば、ファイルやフォルダの作成、削除、移動、コピーなどが簡単にできます。また、パスの扱いにも慣れることができます。
是非、このチュートリアルを参考にして、Pythonでのディレクトリの操作をマスターしてください!
コメント