Python でファイルが存在するかどうかを確認する方法

PythonPythonBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Python で様々な方法を使ってファイルが存在するかどうかを確認する方法を学びます。実験ではまず、ファイルパスについて説明し、絶対パスと相対パスの違いを解説します。サンプルのテキストファイルと Python スクリプトを作成し、現在の作業ディレクトリを取得し、ファイルへの相対パスと絶対パスの両方を定義する方法を実演します。

次に、os.path.exists() 関数と pathlib.Path オブジェクトを使ってファイルの存在を確認する方法を説明します。これらの方法は、ファイルを読み込んだり書き込んだりする前にファイルが存在するかどうかを確実に判断する手段を提供し、Python プログラムでの潜在的なエラーを防ぎます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/FileHandlingGroup(["File Handling"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") python/FileHandlingGroup -.-> python/file_operations("File Operations") python/PythonStandardLibraryGroup -.-> python/os_system("Operating System and System") subgraph Lab Skills python/build_in_functions -.-> lab-559511{{"Python でファイルが存在するかどうかを確認する方法"}} python/importing_modules -.-> lab-559511{{"Python でファイルが存在するかどうかを確認する方法"}} python/standard_libraries -.-> lab-559511{{"Python でファイルが存在するかどうかを確認する方法"}} python/file_operations -.-> lab-559511{{"Python でファイルが存在するかどうかを確認する方法"}} python/os_system -.-> lab-559511{{"Python でファイルが存在するかどうかを確認する方法"}} end

ファイルパスの紹介

このステップでは、Python におけるファイルパスの概念を探ります。ファイルパスを理解することは、ファイルの読み書きや、Python プログラム内でのファイルシステムの操作において重要です。

ファイルパスは、基本的にコンピュータ上のファイルまたはディレクトリのアドレスです。ファイルパスには主に 2 種類あります。

  • 絶対パス: これらのパスは、ファイルシステムのルートディレクトリから始まる、ファイルまたはディレクトリの完全な場所を示します。例えば、Linux システムでは、絶対パスは /home/labex/project/my_file.txt のようになります。
  • 相対パス: これらのパスは、現在の作業ディレクトリを基準としたファイルまたはディレクトリの場所を指定します。例えば、現在の作業ディレクトリが /home/labex/project の場合、相対パス my_file.txt は、絶対パス /home/labex/project/my_file.txt と同じファイルを指します。

まず、VS Code エディタを使って ~/project ディレクトリに簡単なテキストファイルを作成しましょう。my_file.txt という名前の新しいファイルを作成し、以下の内容を追加します。

Hello, LabEx!
This is a test file.

このファイルを ~/project ディレクトリに保存します。

次に、このファイルとやり取りする Python スクリプトを作成しましょう。同じ ~/project ディレクトリに file_paths.py という名前の新しいファイルを作成し、以下のコードを追加します。

import os

## Get the current working directory
current_directory = os.getcwd()
print("Current working directory:", current_directory)

## Define a relative path to the file
relative_path = "my_file.txt"
print("Relative path:", relative_path)

## Define an absolute path to the file
absolute_path = os.path.join(current_directory, relative_path)
print("Absolute path:", absolute_path)

このスクリプトでは、以下のことを行っています。

  • オペレーティングシステムとやり取りするための関数を提供する os モジュールをインポートします。
  • os.getcwd() を使って現在の作業ディレクトリを取得します。
  • my_file.txt ファイルへの相対パスを定義します。
  • os.path.join() を使って、現在の作業ディレクトリと相対パスを結合して絶対パスを作成します。

では、このスクリプトを実行しましょう。VS Code のターミナルを開き、~/project ディレクトリに移動します(デフォルトでそこにいるはずです)。次に、以下のコマンドを使ってスクリプトを実行します。

python file_paths.py

以下のような出力が表示されるはずです。

Current working directory: /home/labex/project
Relative path: my_file.txt
Absolute path: /home/labex/project/my_file.txt

これは、Python で現在の作業ディレクトリを取得し、相対パスと絶対パスの両方を構築する方法を示しています。これらの概念を理解することは、Python プログラムでファイルやディレクトリを操作するための基礎となります。

os.path.exists() の使用

このステップでは、os.path.exists() 関数を使ってファイルまたはディレクトリが存在するかどうかを確認する方法を学びます。これは、ファイル操作における基本的な操作であり、ファイルが存在しない場合やディレクトリが存在しない場合を適切に処理することができます。

os.path.exists() 関数は、1 つの引数を取ります。それは、確認したいファイルまたはディレクトリのパスです。ファイルまたはディレクトリが存在する場合は True を返し、存在しない場合は False を返します。

前のステップで作成した file_paths.py スクリプトを修正して、os.path.exists() を使用しましょう。VS Code エディタで file_paths.py ファイルを開き、以下のコードを追加します。

import os

## 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)

## Check if the file exists using the relative path
if os.path.exists(relative_path):
    print("The relative path 'my_file.txt' exists.")
else:
    print("The relative path 'my_file.txt' does not exist.")

## Check if the file exists using the absolute path
if os.path.exists(absolute_path):
    print("The absolute path", absolute_path, "exists.")
else:
    print("The absolute path", absolute_path, "does not exist.")

## Check if a directory exists
directory_path = current_directory
if os.path.exists(directory_path):
    print("The directory", directory_path, "exists.")
else:
    print("The directory", directory_path, "does not exist.")

## Check if a non-existent file exists
non_existent_file = "non_existent_file.txt"
if os.path.exists(non_existent_file):
    print("The file", non_existent_file, "exists.")
else:
    print("The file", non_existent_file, "does not exist.")

このスクリプトでは、以下のことを行っています。

  • os.path.exists() を使って、相対パスと絶対パスの両方で my_file.txt ファイルが存在するかどうかを確認します。
  • 現在のディレクトリが存在するかどうかも確認します。これは常に存在するはずです。
  • 最後に、存在しないファイルが存在するかどうかを確認します。これは False を返すはずです。

では、再度スクリプトを実行しましょう。VS Code のターミナルを開き、以下のコマンドを使ってスクリプトを実行します。

python file_paths.py

以下のような出力が表示されるはずです。

The relative path 'my_file.txt' exists.
The absolute path /home/labex/project/my_file.txt exists.
The directory /home/labex/project exists.
The file non_existent_file.txt does not exist.

これは、Python プログラムで os.path.exists() を使ってファイルやディレクトリの存在を確認する方法を示しています。これは、ファイルの読み書きを試みる前の重要なステップであり、エラーを防ぎ、プログラムが期待通りに動作することを保証します。

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 でファイルパスとやり取りするための、よりオブジェクト指向的で読みやすい方法を提供します。

まとめ

この実験では、まず Python におけるファイルパスの概念を探索し、絶対パスと相対パスの違いを明らかにしました。絶対パスはファイルの完全な場所を示し、相対パスは現在の作業ディレクトリを基準とした場所を指定することがわかりました。

次に、my_file.txt という名前のテキストファイルと file_paths.py という Python スクリプトを作成し、os.getcwd() を使用して現在の作業ディレクトリを取得する方法と、os モジュールを使用して作成したファイルの相対パスと絶対パスを定義する方法を実証しました。