Open text file in Python package

4

I'm creating a Python package where one of my programs needs to open a text file to read some information. This file is in the same directory as my source. When I run the program in the interpreter I simply do

with open("AtomProva.atp") as f:
    input = f.readlines()

and it opens the file normally. However, when I create a package that runs this program it gives the following error

  

FileNotFoundError: [Errno 2] No such file or directory: 'AtomProva.atp'

How do I find this file by running my function from within the package I'm creating?

    
asked by anonymous 09.12.2016 / 14:35

1 answer

2

Do this:

1- Get the module installation directory:

import os
modulePath = os.path.dirname(os.path.abspath(__file__))

2- Use this path to find the file:

fileName = '{}/AtomProva.atp'.format(modulePath)
with open(fileName) as f:
    input = f.readlines()

If your file is in the package somewhere other than the module where you are reading, use a relative path, such as:

fileName = '{}/../../outro-local/AtomProva.atp'.format(modulePath)
    
09.12.2016 / 20:10