我正在尝试在包is_english_word
中的模块dict.py
中调用函数dictionary
。这是层次结构:
DataCleaning
|___ text_cleaner.py
|___ dictionary
|___ dict.py
|___ list_of_english_words.txt
为了澄清,我在一个名为dict.py
的程序包中有list_of_english_words.txt
和dictionary
。
以下是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
独立于其调用位置?
答案 0 :(得分:3)
问题是您将字符串'__file__'
传递给os.path.realpath
而不是变量__file__
。
变化:
os.path.realpath('__file__')
要:
os.path.realpath(__file__)