I am trying write a list to a csv file. I face several problems.
- writer = csv.writer(f) AttributeError: 'list' object has no attribute 'writer'
I used this link to solve it and it worked, and only printed the second for without writing the first and third for.
this is the code writen by @gumboy
csv = [['1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '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', '1', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0'], ['3', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0']]
csvdict = {words[0]:words[1:] for words in csv}
for x in csvdict.keys(): # iterate over the keys '1', '2', ....
products = [index+1 for index,v in enumerate(csvdict[x]) if v == '1' ] # create list of purchases where the '1's are indexed
print ("costummer", x, "buy", products)
The idea is to replace list that contains 1 with the list index. This problem is solved already. When I used the link above to solve the first problem, the code ran but did not write into the csv file. I tried to combine the solution from the first problem with @gumboy code and here is the code:
csvdict = {words[0]:words[1:] for words in csv}
for x in csvdict.keys(): # iterate over the keys '1', '2', ....
products = [index+1 for index,v in enumerate(csvdict[x]) if v == '1' ] # create list of purchases where the '1's are indexed
#print (products)
f = open("H.csv", 'w')
hasil = ("costummer", x, "buy", products)
hasilstr = (','.join([str(x) for x in hasil]))
print (hasilstr)
f.write(hasilstr)
Like I mentioned above, the code is working but only printed second for without print the first and third element.
print function vs what is written on csv file: print :
costummer,1,buy,[12, 22]
costummer,2,buy,[8, 12, 38, 46]
costummer,3,buy,[4, 34, 43]
csf file :
costummer,2,buy,[8, 12, 38, 46]