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

时间:2016-09-06 11:26:41

标签: python python-os

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

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

为了澄清,我在一个名为dict.py的程序包中有list_of_english_words.txtdictionary

以下是text_cleaner.py中的import语句:

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独立于其调用位置?

1 个答案:

答案 0 :(得分:3)

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

变化:

os.path.realpath('__file__')

要:

os.path.realpath(__file__)