简体   繁体   中英

Only the first and third element printed from python list to csv file

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]

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")

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM