Skip to content Skip to sidebar Skip to footer

Python: Objects Have The Same Value?

I have a csv file which looks like this: 1;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0 2;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0 3;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0 ... 16000;0;0;0;0;0;0;0;0;0;0;0

Solution 1:

You need to move the definition of datensatz from the class. Right now it's a class variable shared across all instances, so it holds the last row created.

Try:

class Datensatz:
    def __init__(self):
        self.datensatz = ['','','','','','','','','','','','','','','','','','']

or better:

class Datensatz:
    def __init__(self, row):
        self.datensatz = row[:]  # [:] is making a shallow copy of the list.


def readCSV():
    with open(path, 'r', encoding = 'iso-8859-15') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=';')
        for row in spamreader:
            #First print
            print(Datensatz(row).datensatz[0])
            dLst.append(Datensatz(row))

    for item in dLst:
        #second print
        print(item.datensatz[0])

Post a Comment for "Python: Objects Have The Same Value?"