Amiga1200
Amiga1200

Reputation: 101

How to build an array of Objects in a loop

I'm new with Python but i'm a Powershell user so maybe what i'm trying to do is not possible the same way in Python

In Python 3 to learn i'm trying to make a list of the files in a directory and store it into a indexstore variable.

To do that this is what i done :

i created 2 objects Index and Indexstore

class Index(object):
def __init__(self, filepath, size):
    self.filepath = filepath
    self.size = size

and

class IndexStore(object):
def __init__(self, filepath, size):
        self.filepath = filepath
        self.size = size

after that i get my filelist from a location on my HDD

listOfFile = os.listdir(SourcePath)

With with list i'm starting a loop where i get the fullpath and the size of the file ( Like ForEach ) in 2 variables fullPath and fileSize

fullPath = os.path.join(SourcePath, entry)
fileSize: int = os.path.getsize(fullPath)

With the values i set the Index Object

setattr(Index, 'filepath', fullPath)
setattr(Index, 'size', fileSize)

And it's working with

pprint(vars(Index))

i have the result

mappingproxy({'dict': <attribute 'dict' of 'Index' objects>, 'doc': None, 'init': <function Index.init at 0x00000271B9C7E940>, 'module': 'main', 'repr': <property object at 0x00000271B9F30590>, 'weakref': <attribute 'weakref' of 'Index' objects>, 'filepath': 'D:\AmigaForever\AmigaOS3.9.ISO', 'size': 28862259})

After that is my problem ! In Powershell if i want to add a object2 to my objectlist1 i just do Objectlist1 += object2 and the work is done but in Python 3.x i tried many things on forums without success best way seems to be :

IndexStore = []
IndexStore.append(Index(fullPath, fileSize))

But the variable Indexstore stay Empty and if i try to print it

print(IndexStore)

pprint(vars(IndexStore))

the run console say :

print(IndexStore) TypeError: 'tuple' object is not callable

Can you help me please ? Do i'm checking the value of my Indexstore well ? Or my error is how i'm appending the values ?

I want in a second loop use again the values of the Object array to continue my code.

Upvotes: 0

Views: 1217

Answers (1)

itprorh66
itprorh66

Reputation: 3288

With the goal of 'Using Python 3 to make a list of the files in a directory and store it into a indexstore variable'.

The first problem I see is that you create a class Indexstore but later completely obviate the class when you assign the variable Indexstore = [].

so given you have a valid list of files from: listOfFile = os.listdir(SourcePath)

This is an approach that will work:

First build an IndexItem class:

class IndexItem:
    def __init__(self, filepath, size):
            self.filepath = filepath
            self.size = size
            
    def __repr__(self):
        # Returns a string representation of the IindexItem
        return f"({self.filepath}, {self.size})"   

This class has an intialization method which serves to preserve the instantiation values passed during initialization and a repr method which is used to convert the index values into readable text.

Next we create the IndexStore Class as follows:

class IndexStore:
    def __init__(self):
        self._index = []
        
    def append(self, o: object):
        # Append an entry onto the index
        self._index.append(o)
        
    def __repr__(self):
        # Returns a string representation of self._index
        return ', '.join(list(str(x) for x in self._index))   

This class includes an instantiation which creates a list to hold the indexItems passed to it, and append method to add IndexItems to the IndexStore and finally a repr to create a readable string of the values.

Finally, we implement the basic functionality required to build the IndexStore as follows:

listOfFile = os.listdir(sourcePath)
index = IndexStore()
for f in listOfFile[:5]:
    # For each entry f in listOfFile 
    fullpath = os.path.join(sourcePath, f)
    # add an instantiation of IndexItem to IndexStore
    index.append(IndexItem(fullpath, int(os.path.getsize(fullpath))))

print(index)    

A simpler and more direct approach to this problem makes use of inherent Python bult-in data structures and capabilities is as follows:

IndexStore = []
listOfFile = os.listdir(sourcePath)
for f in listOfFile[:5]:
    # For each entry f in listOfFile 
    fullpath = os.path.join(sourcePath, f)
    # add an instantiation of IndexItem to IndexStore
    IndexStore.append((fullpath, int(os.path.getsize(fullpath)))

print(IndexStore)    

In this approach, the class definitions are eliminated, and the IndexStore contains a list of tuples with each tuple containing the fullpath to the file and it's size

Upvotes: 1

Related Questions