Python - How to open a file inside a module?

Viewed 2650

I've something like this in my program: A main script main.py inside a folder named 'OpenFileinaModule'. There's a folder called 'sub' inside it with a script called subScript.py and a file xlFile.xlsx, which is opened by subScript.py.

OpenFileinaModule/
             main.py
             sub/
             __init__.py   (empty)
             subScript.py
             xlFile.xlsx

Here is the code:

sub.Script.py:

import os, openpyxl

class Oop:
    def __init__(self):
        __file__='xlFile.xlsx'
        __location__ = os.path.realpath(
            os.path.join(os.getcwd(), os.path.dirname(__file__)))
        print os.path.join(__location__, __file__)

        self.wrkb = openpyxl.load_workbook(os.path.join(__location__, 
__file__),read_only=True)

main.py:

import sub.subScript
objt=sub.subScript.Oop()

When I execute main.py, I get the error:

IOError: [Errno 2] No such file or directory: 'C:\\Users\\...\\OpenFileInaModule\\xlFile.xlsx'

It jumps the sub folder... I've tried

__file__='sub/xlFile.xlsx'

But then the "sub" folder is duplicated:

IOError: [Errno 2] No such file or directory: 'C:\\Users\\...\\OpenFileInaModule\\sub\\sub/xlFile.xlsx'

How to open xlFile.xlsx with subScript.py from main.py?

2 Answers
Related