LoginSignup
0
0

Pythonでパスとフォルダを操作するには、主にosモジュールとpathlibモジュールを使用します。pathlibモジュールは比較的新しく、より直感的な操作が可能です。ここでは両方を紹介します。

パスの操作

まず、現在の作業ディレクトリを取得する方法から見てみましょう。

import os
from pathlib import Path

# osモジュールを使用
current_dir_os = os.getcwd()
print(f"現在のディレクトリ (os): {current_dir_os}")

# pathlibモジュールを使用
current_dir_pathlib = Path.cwd()
print(f"現在のディレクトリ (pathlib): {current_dir_pathlib}")

ファイルやフォルダの存在確認

次に、特定のファイルやフォルダが存在するかどうかを確認する方法を見てみましょう。

import os
from pathlib import Path

# ファイルパスを指定
file_path = "example.txt"

# osモジュールを使用
if os.path.exists(file_path):
    print(f"{file_path} が存在します")
else:
    print(f"{file_path} が存在しません")

# pathlibモジュールを使用
path = Path(file_path)
if path.exists():
    print(f"{file_path} が存在します")
else:
    print(f"{file_path} が存在しません")

フォルダの作成

新しいフォルダを作成する方法を紹介します。

import os
from pathlib import Path

# 新しいフォルダ名
new_folder = "new_directory"

# osモジュールを使用
if not os.path.exists(new_folder):
    os.mkdir(new_folder)
    print(f"{new_folder} を作成しました")
else:
    print(f"{new_folder} は既に存在します")

# pathlibモジュールを使用
path = Path(new_folder)
if not path.exists():
    path.mkdir()
    print(f"{new_folder} を作成しました")
else:
    print(f"{new_folder} は既に存在します")

ファイル一覧の取得

特定のディレクトリ内のファイルとフォルダの一覧を取得する方法を見てみましょう。

import os
from pathlib import Path

# osモジュールを使用
print("osモジュールを使用:")
for item in os.listdir():
    print(item)

# pathlibモジュールを使用
print("\npathlibモジュールを使用:")
current_dir = Path(".")
for item in current_dir.iterdir():
    print(item)

これらの例を通じて、Pythonでのパスとフォルダ操作の基本を理解していただけたかと思います。pathlibモジュールは、より直感的でオブジェクト指向的なアプローチを提供しており、多くの場面でosモジュールよりも使いやすいです。

参考) 東京工業大学情報理工学院 Python早見表

0
0
0

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