0

I made my own python module that I want to be able to import from anywhere. The module I created relies of a text file of information in order to run.

I ran python -m site --user-site, and created that directory and I put a copy of my module, and the text file into the site-packages directory, restarted IDLE and then attempted to import my module. I ran into this error:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import MyModule
  File "C:\Users\User\AppData\Roaming\Python\Python27\site-packages\MyModule.py", line 34, in <module>
    with open('TextFile.txt') as p:
IOError: [Errno 2] No such file or directory: 'TextFile.txt'

This is what my module looked like:

import blah

...

with open('TextFile.txt') as p:
    p.read()

why is this error happening? The file is in the same directory!

1 Answers1

0

It turns out that when you import a site-package, it gets executed in the current directory, not in the site-packages directory.

The way you can fix this error is to specify the path to the file you want.
For example, you would change line 34 of MyModule, to match this code:

with open('C:\Users\User\AppData\Roaming\Python\Python27\site-packages\TextFile.txt') as p:

Alternatively, you could either change the current directory to site-packages, or get a copy of the needed file (in this case TextFile.txt) in the current directory as a quick fix without modifying your module.