Reading a file from the directory which module is imported

Viewed 97

I am trying to read a file in a custom module I have created in Python. But it is showing error when I try to do so.

Directory structure

base/
|
|_ app.py
|_ cmod/
   |
   |_ __init__.py
   |_ util.py
   |_ db.csv

util.py snippet

from csvhandler import CSVFile

def get_db():
    with open("db.csv", "r+") as db:
        data = CSVFile(db)
    return data

app.py snippet

from cmod import util
data = util.get_db()

It throws the following error

FileNotFoundError: [Errno 2] No such file or directory: 'db.csv'

Is there any issue with imports of placement?
Note: The db.csv has to be put there only.

1 Answers

The current working directory when you run this is likely the one app.py sits in. open() looks for files in the current working directory, not the directory of the currently executing file.

The most portable way to open a file stored relatively would be to get the full path to the python file, isolate the directory, and then join it.

util.py

import os

def get_db():
    directory = os.path.dirname(__file__)
    with open(os.path.join(directory, "db.csv"), "r+") as db:
        data = CSVFile(db)
    return data
Related