Skip to content
Advertisement

When import a python file into another (in a subdirectory) it stops finding the csv in the same directory

I’m trying to import the cleaning file in the managers file like this:

import sys
import os

sys.path.append(os.path.dirname(os.path.abspath("cleaning.py")))
from cleaning import df_invoices_full

The main folder contains the files cleaning, transaction listing and a sub folder called “apps” with the managers file:

enter image description here

Also note that the cleaning file reads the transaction listing.csv file.

The issue I’m getting when running is:

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

And “Transaction Listings.csv” is correctly loaded by cleaning but no when cleaning is imported into maganagers.

Appreciate your help.

Advertisement

Answer

#-- cleaning.py --#

import os
import pandas as pd

csv_filename = "Transaction Listings.csv"
folder = os.path.dirname(os.path.abspath(__file__))
path_to_csv = os.path.join(folder, csv_filename)

df_invoices_full = pd.read_csv(path_to_csv, encoding="latin-1") 

Use this code in cleaning.py instead of your current code.

What is happening is that when cleaning.py is imported into apps/managers.py, it runs in the apps folder, not the base folder where the CSV files are located. By giving the absolute path, pd.read_csv() will look in the correct place for the file – the directory that cleaning.py actually resides in. See what does the __file__ variable mean/do?.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement