0

I'm writing a simple Python module (called event_classifier) for a project that I'm currently working on and am having the following issue. There is a text file (categories.txt) that contains several strings that I need to read using various functions in the module. However, when I import the classes from the module using the following command

from event_classifier import *

I get an error, because the functions open categories.txt using the relative path to the file within the event_classifier directory. Thus, when I import the module, the file is not imported with it, so it no longer exists there.

By the way, my __init__.py file inside event_classifier just has the following

from Event import *
from alg import *

(it just imports all of the classes and functions from the other files in the module).

Has anyone had this problem before and was able to come up with a working solution?

Ryan
  • 7,621
  • 5
  • 18
  • 31
  • 1
    Are you actually trying to _import_ that text file, or just `open` it and read text from it? – abarnert Jun 05 '15 at 06:46
  • possible duplicate of [Relative file paths in Python packages](http://stackoverflow.com/questions/1011337/relative-file-paths-in-python-packages) – three_pineapples Jun 05 '15 at 06:58
  • Are you sure it is opening the file relative to the module's directory? Can we see the error that is being produced please? (full traceback) – cdarke Jun 05 '15 at 07:12

1 Answers1

0

A relative path is, by default, relative to the current working directory.

If you're trying to open a file at a fixed location relative to your module instead, you have to do that explicitly.

For example:

import os

module_dir = os.path.dirname(os.path.abspath(__file__))
textfile_path = os.path.join(module_dir, 'categories.txt')
with open(textfile_path) as f:
    # etc.

However, this usually isn't the best solution. It's better to design a complex package like this to be installed, rather than used directly in the source tree, and use setuptools features to put data files in a (platform-appropriate) standard location at install time, and then access them from that location at runtime using the pkg_resources API.

abarnert
  • 354,177
  • 51
  • 601
  • 671