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

2024-05-29 06:01:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图调用包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语句:

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的导入独立于调用它的位置?你知道吗


Tags: ofpathtextpytxtdictionaryenglishos
1条回答
网友
1楼 · 发布于 2024-05-29 06:01:24

问题是您将字符串'__file__'传递给os.path.realpath,而不是变量__file__。你知道吗

更改:

os.path.realpath('__file__')

收件人:

os.path.realpath(__file__)

相关问题 更多 >

    热门问题