0

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;0;0;0;0;0;0

I wrote the following Python Script:

import csv

path = 'pathToCSV.csv'
dLst = []

class Datensatz:
    #0:schluesse 1:straftat 2:gemeindeSchluessel 3:stadt 4:kreisart 5:erfassteFaelle 6:HZnachZensus
    #7:versucheAnzahl 8:versucheInProCent 9:mitSchusswaffeGedroht 10:mitSchusswaffeGeschossen=
    #11:aufgeklaerteFaelle 12:aufklaerungsquote 13:tatverdaechtigeInsgesamt 14:tatverdaechtigeM
    #15:tatverdaechtigeW 16:nichtdeutscheTatverdaechtigeAnzahl 17:NichtdeutscheTatverdaechtigeInProCent
    datensatz =['','','','','','','','','','','','','','','','','','']


def createDatensatz(row):
    d = Datensatz()
    for i in range(0,17):
        d.datensatz[i] = row[i]
    return d


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

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


if __name__ == "__main__":
    readCSV()

For the first print in my code, I get all numbers from 1 to 16000 which is correct!

But for the second print after adding the objects to my list I get 16000 times the last value.

16000
16000
16000
...
16000

Why? Where is the problem?

1
  • 1
    Datensatz.datensatz is a class member and is shared between all instances of Datensatz. You have to create an __init__ for your class and initialize instance members there. Commented Apr 14, 2017 at 2:11

1 Answer 1

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.