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?
Datensatz.datensatzis a class member and is shared between all instances ofDatensatz. You have to create an__init__for your class and initialize instance members there.