0

I have a python (3) module and it needs to open a file to get data. I want to import this module into other python programs, but when I try it fails because it cannot find the data file.

The data file is stored in the same folder as the python module. I would have assumed that the file would still check its local path even when imported.

How can I get this to work?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
user668074
  • 1,111
  • 10
  • 16

1 Answers1

0

Assuming a directory structure like this:

.
├── bar
│   ├── __init__.py
│   └── foo.py
└── main.py

In your main.py script you could create an absolute path:

import os
import bar.foo as myFoo

dataFilePath = os.path.join(os.path.dirname(myFoo.__file__), 'data.csv')
print(dataFilePath)
myFoo.load(dataFilePath)

This generates an absolute path for the data file:

/tmp/bar/data.csv
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47