pathlib.Path で確認する
このステップでは、pathlib
モジュールを探索します。このモジュールは、ファイルやディレクトリとの相互作用をオブジェクト指向的に行う方法を提供します。具体的には、pathlib.Path
を使ってファイルやディレクトリの存在を確認する方法に焦点を当て、os.path.exists()
の代替手段を紹介します。
pathlib
モジュールは、古い os.path
モジュールに比べて、より現代的で直感的なファイルパス操作のアプローチを提供します。このモジュールはファイルパスをオブジェクトとして表現し、それらのオブジェクトのメソッドを使って様々な操作を行うことができます。
これまで作業してきた file_paths.py
スクリプトを修正して、pathlib.Path
を使用しましょう。VS Code エディタで file_paths.py
ファイルを開き、以下のコードを追加します。
import os
from pathlib import Path
## Get the current working directory
current_directory = os.getcwd()
## Define a relative path to the file
relative_path = "my_file.txt"
## Define an absolute path to the file
absolute_path = os.path.join(current_directory, relative_path)
## Create Path objects for relative and absolute paths
relative_path_obj = Path(relative_path)
absolute_path_obj = Path(absolute_path)
## Check if the file exists using the relative path object
if relative_path_obj.exists():
print("The relative path 'my_file.txt' exists (using pathlib).")
else:
print("The relative path 'my_file.txt' does not exist (using pathlib).")
## Check if the file exists using the absolute path object
if absolute_path_obj.exists():
print("The absolute path", absolute_path, "exists (using pathlib).")
else:
print("The absolute path", absolute_path, "does not exist (using pathlib).")
## Check if a directory exists using pathlib
directory_path_obj = Path(current_directory)
if directory_path_obj.exists():
print("The directory", current_directory, "exists (using pathlib).")
else:
print("The directory", current_directory, "does not exist (using pathlib).")
## Check if a non-existent file exists using pathlib
non_existent_file = "non_existent_file.txt"
non_existent_path_obj = Path(non_existent_file)
if non_existent_path_obj.exists():
print("The file", non_existent_file, "exists (using pathlib).")
else:
print("The file", non_existent_file, "does not exist (using pathlib).")
このスクリプトでは、以下のことを行っています。
pathlib
モジュールから Path
クラスをインポートします。
my_file.txt
の相対パスと絶対パスの両方に対して Path
オブジェクトを作成します。
Path
オブジェクトの exists()
メソッドを使って、ファイルが存在するかどうかを確認します。
pathlib
を使って、現在のディレクトリと存在しないファイルの存在を確認します。
では、再度スクリプトを実行しましょう。VS Code のターミナルを開き、以下のコマンドを使ってスクリプトを実行します。
python file_paths.py
以下のような出力が表示されるはずです。
The relative path 'my_file.txt' exists (using pathlib).
The absolute path /home/labex/project/my_file.txt exists (using pathlib).
The directory /home/labex/project exists (using pathlib).
The file non_existent_file.txt does not exist (using pathlib).
これは、ファイルやディレクトリの存在を確認するために、os.path.exists()
の代替として pathlib.Path
を使用する方法を示しています。pathlib
モジュールは、Python でファイルパスとやり取りするための、よりオブジェクト指向的で読みやすい方法を提供します。