1
1

Pythonを初心者の頃、以下のようなコードでファイルが見つからず悩んだ。

file_not_found.py
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ファイル自体のパスが得られる。文字列の操作でもパスをつくることができるが、ospathlibを使うと簡単にパスが作れる。osでは文字列のままパスを操作し、pathlibではPathオブジェクトを作ってから操作をしている。この場合、ファイルのパス自体は絶対パスになっているので、作業ディレクトリがPythonファイルのディレクトリと異なることが問題にならない。

os_ver.py
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())
pathlib_ver.py
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を使って、作業ディレクトリを変更することができる。

chdir_ver.py
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など日本語のパスを受け付けない場合にも、作業ディレクトリを変えることで問題なく開くことができる(無論ファイル名はアルファベットである必要がある)。

1
1
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
1
1