Pythonを初心者の頃、以下のようなコードでファイルが見つからず悩んだ。
with open("test.txt") as file:
print(file.read())
VScode上でPythonファイルをディレクトリで開かずに、再生ボタンを押して実行していたことがこの問題の原因である。この場合、作業ディレクトリがPythonファイルの存在するディレクトリではない。Pythonファイルからみた相対パスで指定するとFileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
と注意されてしまう。
再生ボタンを押すだけで実行可能という利便性を持たせつつ、ファイルのパスを正しく指定する解決法を2つ示す。
pythonファイルのパスから絶対パスをつくる
Pythonでは__file__
からそのPythonファイル自体のパスが得られる。文字列の操作でもパスをつくることができるが、os
やpathlib
を使うと簡単にパスが作れる。os
では文字列のままパスを操作し、pathlib
ではPathオブジェクトを作ってから操作をしている。この場合、ファイルのパス自体は絶対パスになっているので、作業ディレクトリがPythonファイルのディレクトリと異なることが問題にならない。
import os
# Pythonファイルのあるディレクトリ
directory_str = os.path.join(__file__, os.pardir)
# test.txtの絶対パス
test_file_str = os.path.join(directory_str, "test.txt")
with open(test_file_str) as file:
print(file.read())
import pathlib
# Pythonファイルのあるディレクトリ
directory_path = pathlib.Path(__file__).parent
# test.txtの絶対パス
test_file_path = directory_path.joinpath("test.txt")
with open(test_file_path) as file:
print(file.read())
プログラム上で作業ディレクトリを変更する
os.chdir
を使って、作業ディレクトリを変更することができる。
import os
# Pythonファイルのあるディレクトリ
directory_str = os.path.join(__file__, os.pardir)
os.chdir(directory_str)
with open("test.txt") as file:
print(file.read())
opencv
など日本語のパスを受け付けない場合にも、作業ディレクトリを変えることで問題なく開くことができる(無論ファイル名はアルファベットである必要がある)。