Papouche Guinslyzinho
Papouche Guinslyzinho

Reputation: 5448

how to setup a path within a python package

I'm creating a package, first I install it locally python setup.py develop I am having an issue when I call the program

>>> import cstm.artefact as art
>>> art.what_is('Objname', 'en')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/home/guinsly/development/public/project/jeunesse/canadian_science_and_t
echnology_museum_api/cstm/artefact.py", line 56, in what_is
    valeur = open_file(keywords, lang)
  File "/home/guinsly/development/public/project/jeunesse/canadian_science_and_t
echnology_museum_api/cstm/artefact.py", line 24, in open_file
    book = xlrd.open_workbook(path)
  File "/usr/lib/python2.7/dist-packages/xlrd/__init__.py", line 394, in open_wo
rkbook
    f = open(filename, "rb")
IOError: [Errno 2] No such file or directory: '/home/guinsly/cstm/data/data.xls'

So the package that I'm creating is on this path /home/guinsly/development/public/project/jeunesse/canadian_science_and_technology_museum_api/cstm/

but the package try to open the .xls file where I'm when I ran the bpython console.

On my package my test are ok

-> % py.test -v
============================== test session starts ==============================
platform linux -- Python 3.4.0 -- py-1.4.26 -- pytest-2.6.4 -- /usr/bin/python3
plugins: quickcheck
collected 4 items 

test_artefact.py::TestArtefact::test_definition PASSED
test_artefact.py::TestArtefact::test_definition_fr PASSED
test_artefact.py::TestArtefact::test_definition_not_found PASSED
test_artefact.py::TestArtefact::test_definition_not_found_fr PASSED

=========================== 4 passed in 0.09 seconds ============================
guinsly@guinsly-ThinkPad-L430 [09:46:33] [~/development/public/project/jeunesse/canadian_science_and_technology_museum_api]

Question: How can I set my path properly on this function

def open_file(keywords, lang = 'en'):
    """
    Open and read an Excel file
    """
    directory = os.getcwd()
    path = directory+"/cstm/data/data.xls"

....

Upvotes: 1

Views: 92

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121904

You are using a path relative to the current working directory, not relative to your project. The current working directory is set by the user (based on their current location in their terminal, for example).

Use the __file__ global of your module to determine your module location:

import os

module_path = os.path.dirname(os.path.abspath(__file__))

and base the file path relative to that:

path = os.path.join(module_path, "cstm/data/data.xls")

Upvotes: 3

Related Questions