LoginSignup
63
49

More than 5 years have passed since last update.

【備忘録】Pythonでの親ディレクトにあるファイルのimport

Posted at

親ディレクトリに置かれているスクリプトファイルをimportしたい場合には、次のようにすると可能になります。この例では、親ディレクトに置かれているtools.pyファイルをimportしています。

>>> import sys,os
>>> sys.path.append(os.pardir)
>>> import tools
  • os.pardirは、親ディレクトリを表す文字列定数となっています。
  • sys.pathは、importするファイルを検索するパスを示す文字列のリストです。PYTHONPATH 環境変数と、インストール先でのデフォルトパスで初期化されます。ですので、sys.pathにimportしたいファイルのディレクトリを含めれば、適当なディレクトリに置かれているスクリプトファイルをimport出来ます。 当然、パーミッションの設定によっては、出来ない場合もあると思いますが。
63
49
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
63
49