简体   繁体   中英

Create a Class that creates a dictionary from reading in Multiple CSV Files - Python

I have 24 csv files that currently reside in a folder directory. The goal is to read all the CSV files in and store them as individual pandas dataframes. At the request of my client, they wish all of our code to be in Object Oriented Programming. I am new to OOP and I would appreciate any help.

I am currently trying to create a class that will read in my files and store them as a dictionary via a for loop. With the key being the name of the file, and the value being the pandas dataframe

I already have a list of filepaths stored in aa variable called fns

This is what I have for the code so far, I jam trying to figure out the loop logic so I don't have to call a new class instance every time.

fns = glob.glob(path + "*.csv")
enc = 'ISO-8859-1'

# create class

class MyFile:

    def __init__(self, file_path):
        self.file = file_path

    def ParseName(self):
        self.name_me = self.file.split('\\')[-1].strip('.csv')

    def Read_CSV(self):
        self.data_csv = pd.read_csv(self.file,delimiter='\t',
                                    low_memory=False, encoding= enc)

My goal is to get a dictionary like this:

{'filename1': DataFrame, 'filename2': DataFrame, .... 'filename24': DataFrame}

I appreciate all the help!

Sample Object-oriented CsvStorage :

import glob
import pandas as pd
from os.path import basename

class CsvStorage:

    _dfs = {}

    def __init__(self, path):
        for f in glob.glob(path):
            self._dfs[basename(f)] = pd.read_csv(f, encoding='ISO-8859-1')

    def get_dataframes(self):
        if not self._dfs:
            raise ValueError('No dataframes. Load data first')

        return self._dfs

files_path = '*/FILE_*.csv'   # adjust to your actual path pattern
csv_store = CsvStorage(files_path)
dfs = csv_store.get_dataframes()

print(dfs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM