2

I am trying write a list to a csv file. I face several problems.

  1. 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]
Paula Livingstone
  • 1,175
  • 1
  • 12
  • 21
Tanabata
  • 31
  • 7

2 Answers2

1

What you are doing with the f = open('H.csv','w') is that it is write to the file but also writing over your data. What you need to do is use f =open('H.csv', 'a+') this appends new string everytime to the file.link To sort data use

for x in sorted(csvdict.keys()):

With this code I was able to write to file what was printed on console.

csvfile = [['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 csvfile}
for x in sorted(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", 'a+')
    hasil = ("costummer", x, "buy", products)
    hasilstr = ("costummer, %s,buy,"+','.join([str(i) for i in products])) %(x)
    print (hasilstr)
    f.write(hasilstr +"\n")
Gumboy
  • 467
  • 4
  • 8
  • yeah that's interesting, i did't notice is because they print second element and not the third element. so by converting the list into str is the right move sir ? the other things is why it won't print the last (third for) element ? – Tanabata Oct 29 '17 at 16:42
  • What is your desire csv output? – Gumboy Oct 29 '17 at 16:49
  • CMIIW, they will write what they print right ? i mean i just wanna clarified what am i doing above is not abused the looping logic. since print and write hasilstr, they should write what it print right ? i this case they print : costummer,1,buy,[12, 22], costummer,2,buy,[8, 12, 38, 46], costummer,3,buy,[4, 34, 43], but they only printed costumer 1 and 2. – Tanabata Oct 29 '17 at 16:57
  • Did that help you? – Gumboy Oct 29 '17 at 17:07
  • there must be wrong with my pc becasue i copy you code 100% and it print 3 costumer and still just print 2 costumer in csv lol. – Tanabata Oct 29 '17 at 17:19
1

The problem is that you open the file again for each iteration of the for loop (open it just once) and then overwrite it because you pass 'w' as the 'mode' argument (if you just want to append something to the file you can pass 'a').

What you should actually do is, import the csv module, open the file with a with statement, create a writer writer = csv.writer(csv_file), write the header and then the rows in the for loop. (Also, rename the csv list, because csv is the name of the module.)

import csv


lst = [...]  # Your csv list.
csvdict = {words[0]:words[1:] for words in lst}

with open('temp.csv', 'w', newline='') as csv_file:
    writer = csv.writer(csv_file, delimiter=';')
    writer.writerow(('costumer', 'buy'))  # Write the header.
    for costumer in csvdict:
        products = [index for index, v in enumerate(csvdict[costumer], 1) if v == '1']
        writer.writerow((costumer, products))

The resulting csv file will look like this (the first column contains the costumers and the second the products):

costumer;buy
3;[4, 34, 43]
2;[8, 12, 38, 46]
1;[12, 22]
skrx
  • 19,980
  • 5
  • 34
  • 48
  • 1
    thank you sir, I am just curious can we remome the " " ? i try to remove the list braked and the "" so far i used your code like this = products1 = " ,".join(str(x) for x in products) writer.writerow((costumer, products1)) and it remove the list braked but still have know idea how to remove the "" – Tanabata Oct 29 '17 at 17:17
  • 1
    The csv writer had to add the quotes because commas were used as the delimiters and because a list also uses commas to separate the items. You can prevent this by passing a different delimiter like semicolon. I've edited the example. – skrx Oct 29 '17 at 17:25
  • 1
    muchas gracias sir. – Tanabata Oct 29 '17 at 17:28
  • 1
    You're welcome. Also, it seems that storing your data in a [json](https://docs.python.org/3/library/json.html) file could be a better alternative. – skrx Oct 29 '17 at 17:30
  • 1
    thank you sir, next time i will try to used json file instead. – Tanabata Oct 29 '17 at 17:34