1
0

More than 1 year has passed since last update.

名前にハイフンが含まれるファイルをインポートする方法

Last updated at Posted at 2021-11-02

Pythonでファイル名に-(ハイフン)が含まれるファイルをモジュールとして「import」を使って読み込もうとしたらエラーが発生し、正常にインポートできなかったので解決した方法をまとめておく。

importの使い方

import文は、次のように使用したいモジュールを指定する。

import <モジュール名>

問題

このimportを使用してファイル名に-(ハイフン)が含まれるファイルをモジュールとしてインポートしようとすると以下のようになる。

// importの部分
import test-file

// エラー
import test-file
           ^
SyntaxError: invalid syntax

このように、SyntaxErrorが発生してしまい正常にインポートすることができない。

解決策

import_module()を使用してモジュールをインポートすることで解決した。これを使用する場合は、importlibをインポートする必要がある。

import importlib

module = importlib.import_module("test-file")
1
0
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
0