How to import a module which opens a file in the same directory as the module?
<p>I am trying to call a function <code>is_english_word</code> in a module <code>dict.py</code> in package <code>dictionary</code>. Here is the hierarchy:</p>

<pre><code>DataCleaning
|___ text_cleaner.py
|___ dictionary
     |___ dict.py
     |___ list_of_english_words.txt
</code></pre>

<p>To clarify, I have <code>dict.py</code> and <code>list_of_english_words.txt</code> in one package called <code>dictionary</code>. </p>

<p>Here is the import statement written in <code>text_cleaner.py</code>:</p>

<p><code>import DataCleaning.dictionary.dict as dictionary</code></p>

<p>and, here is the code written in <code>dict.py</code>:</p>

<pre><code>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
</code></pre>

<p>But when I run the <code>text_cleaner.py</code> file, it shows an import error as it cannot find the <code>list_of_english_words.txt</code>:</p>

<pre><code>Traceback (most recent call last):
  File "E:/Analytics Practice/Social Media Analytics/analyticsPlatform/DataCleaning/text_cleaner.py", line 1, in &lt;module&gt;
    import DataCleaning.dictionary.dict as dictionary
  File "E:\Analytics Practice\Social Media Analytics\analyticsPlatform\DataCleaning\dictionary\dict.py", line 3, in &lt;module&gt;
    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'
</code></pre>

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

<p>The issue is that you are passing the string <code>'__file__'</code> to <code>os.path.realpath</code> instead of the variable <code>__file__</code>.</p>

<p>Change:</p>

<pre><code>os.path.realpath('__file__')
</code></pre>

<p>To:</p>

<pre><code>os.path.realpath(__file__)
</code></pre>

python python-os