Open text file in Python package

Asked

Viewed 338 times

5

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 he 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?

  • I don’t know how it is to create packages but surely you have a path problem. In your code you pass a relative path of a file in the same folder as yours. py, at the time it will run the package it looks elsewhere (I don’t know exactly which). Pass more details of what it is and how uses this package that can reach the solution.

  • It is a simple package (a folder with a init.py, your script plus your . atp) or a package generated with setuptools?

1 answer

3

Do it like 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 at some location other than the module where you are reading, use a relative path, for example:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.