-1

I have created a Python package and installed locally. With using the command pip install . .In my package it's necessary to open a file like this.

open('abc.txt','r+')

But my problem is it's try to open the file in the working directory instead of package installed directory.I think absolute path not going to solve my problem.

So my question is, How open a file inside the package ?

NB: While i searched about it saw that os.sys.path may help. But i didn't get any clear solution.

Thank you,

Rahul K P
  • 15,740
  • 4
  • 35
  • 52
  • Possible duplicate of [Python: How to read a (static) file from inside a package?](http://stackoverflow.com/questions/6028000/python-how-to-read-a-static-file-from-inside-a-package) – Alastair McCormack Mar 13 '17 at 14:15

1 Answers1

1

You can try like this:

import os
import inspect  

def open_file(filename):
  pkg_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
  return open(pkg_dir + "/" + filename,'r+')
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
Nima Ghotbi
  • 641
  • 3
  • 9