如何导入在与模块相同的目录中打开文件的模块?

How to import a module which opens a file in the same directory as the module?

我正在尝试调用程序包 dictionary 中模块 dict.py 中的函数 is_english_word。这是层次结构:

DataCleaning
|___ text_cleaner.py
|___ dictionary
     |___ dict.py
     |___ list_of_english_words.txt

澄清一下,我在一个名为 dictionary 的包中有 dict.pylist_of_english_words.txt

这里是text_cleaner.py中写的导入语句:

import DataCleaning.dictionary.dict as dictionary

并且,这里是 dict.py 中编写的代码:

import os

with open(os.path.join(os.path.dirname(os.path.realpath('__file__')), 'list_of_english_words.txt')) as word_file:
    english_words = set(word.strip().lower() for word in word_file)


def is_english_word(word):
    return word.lower() in english_words

但是当我 运行 text_cleaner.py 文件时,它显示导入错误,因为它找不到 list_of_english_words.txt:

Traceback (most recent call last):
  File "E:/Analytics Practice/Social Media Analytics/analyticsPlatform/DataCleaning/text_cleaner.py", line 1, in <module>
    import DataCleaning.dictionary.dict as dictionary
  File "E:\Analytics Practice\Social Media Analytics\analyticsPlatform\DataCleaning\dictionary\dict.py", line 3, in <module>
    with open(os.path.join(os.path.dirname(os.path.realpath('__file__')), 'list_of_english_words.txt')) as word_file:
FileNotFoundError: [Errno 2] No such file or directory: 'E:\Analytics Practice\Social Media Analytics\analyticsPlatform\DataCleaning\list_of_english_words.txt'

但是当我 运行 dict.py 代码本身时,它没有显示任何错误。我可以清楚地看到 os.path.dirname(os.path.realpath('__file__')) 指向 text_cleaner.py 而不是 dict.py 的目录。如何使我的模块 dict.py 的导入独立于它的调用位置?

问题是您将字符串 '__file__' 传递给 os.path.realpath 而不是变量 __file__

变化:

os.path.realpath('__file__')

收件人:

os.path.realpath(__file__)