1

I am trying to call a function is_english_word in a module dict.py in package dictionary. Here is the hierarchy:

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

To clarify, I have dict.py and list_of_english_words.txt in one package called dictionary.

Here is the import statement written in text_cleaner.py:

import DataCleaning.dictionary.dict as dictionary

and, here is the code written in 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

But when I run the text_cleaner.py file, it shows an import error as it cannot find the 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'

But when I run the dict.py code itself, it shows no error. I can clearly see that the os.path.dirname(os.path.realpath('__file__')) points to the directory of text_cleaner.py and not of dict.py. How do I make the import of my module dict.py independent of from where it is called?

4

1 回答 1

3

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

改变:

os.path.realpath('__file__')

至:

os.path.realpath(__file__)
于 2016-09-06T11:40:21.827 回答