1

I'm currently trying to write a list to a csv file so that there are x values per row (with the number of values being a multiple of x). I have been searching for a solution for a while now and I have found a number of ways to approach the subject but I cannot seem to get the code to do what I want.

This is my hypothetical example... I have tried to zip the list so that is is a list of lists in an attempt to have it write 2 values per row. There is no use though; this is what happens...

I want my list in the .txt file to look like this:

Chocolates,3
Novels,14
Pens,4
Smiles,78

but in my coding, it looks like this...

record1 = ['Chocolates', '3', 'Novels', '14', 'Pens', '4', 'Smiles', '78']

I used this to zip it:

records = [record1[i:i+2] for i in range(0, len(record1), 2)]

prize = open("box.txt","w")
writer = csv.writer(prize)
writer.writerow(records)

However, it looks like this in the txt file

"['Chocolates', '3']","['4', '14']","['Pens', '4']","['Smiles', '78']"

I've also tried to write the list to the file differently...

prize = open("box.txt","w")
writer = csv.writer(prize)
for record in records:
    writer.writerow(records)
prize.close()

But it appears like this:

"['Chocolates', '3']","['hiii', '14']","['Pens', '4']","['Smiles', '78']"
"['Chocolates', '3']","['hiii', '14']","['Pens', '4']","['Smiles', '78']"
"['Chocolates', '3']","['hiii', '14']","['Pens', '4']","['Smiles', '78']"
"['Chocolates', '3']","['hiii', '14']","['Pens', '4']","['Smiles', '78']"

I do not know if I'm on the right track or if my approach is right. I was thought that the appearance depended on the list's appearance, however, I'm beginning to believe that it depends on the way I write it to the file.

Thank you for reading. Hopefully my explanation was clear, sorry if it was not.

Tamz.001
  • 15
  • 2
  • `>>> record1 = ['Chocolates', '3', 'Novels', '14', 'Pens', '4', 'Smiles', '78'] >>> [record1[i:i+2] for i in range(0, len(record1), 2)] [['Chocolates', '3'], ['Novels', '14'], ['Pens', '4'], ['Smiles', '78']]` – Natecat Feb 06 '17 at 23:09
  • Unless you are just trying to learn the `csv` model, your case would be easier to just write out directly. For general regrouping (i.e., partitioning), see http://stackoverflow.com/questions/3992735/python-generator-that-groups-another-iterable-into-groups-of-n – Alan Feb 06 '17 at 23:19

3 Answers3

1

In the first case you should be using writerows(), not writerow():

writer.writerows(records)

In the second case it should be:

for record in records:
    writer.writerow(record)    # record, not records

Demo

Try pasting this into a Python shell:

import csv

record1 = ['Chocolates', '3', 'Novels', '14', 'Pens', '4', 'Smiles', '78']
records = [record1[i:i+2] for i in range(0, len(record1), 2)]

with open("box.txt", "w") as prize:
    writer = csv.writer(prize)
    writer.writerows(records)

After running this code box.txt contains:

Chocolates,3
Novels,14
Pens,4
Smiles,78
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • Are you sure about the latter? Each character in my file is written to have a comma between them e.g. c,h,o,c,o,l,a,t,e,s,3 etc... – Tamz.001 Feb 06 '17 at 23:20
  • @Tamz.001: that will happen if you attempt `for record in record1:`. Do not confuse `record1` with `records` which is the grouped by N list. – mhawke Feb 06 '17 at 23:26
  • Yep, I did it how you said but that still happened. Thank you for your help though. – Tamz.001 Feb 06 '17 at 23:35
  • @Tamz.001: then you must be doing something differently - it works for me. I've added a full example to my answer; try pasting that verbatim into a Python shell. – mhawke Feb 06 '17 at 23:42
0

You called a wrong method. Must be:

prize = open("box.csv","w")
writer = csv.writer(prize)
writer.writerows(records)
DYZ
  • 55,249
  • 10
  • 64
  • 93
  • Oh thanks-I didn't realise that. The only problem is, that now, the values appear like this in the text file: Chocolates,3 hiii,14 Pens,4 Smiles,78 **four times – Tamz.001 Feb 06 '17 at 23:14
  • I think we are talking about different solutions. My answer refers to your _first_ snippet. And how did you open the file? In Excel? – DYZ Feb 06 '17 at 23:17
  • Nope, I'm using a text file (notepad). And sorry if my explanation wasn't clear enough but the two attempts I showed was for the same aim: to print x (in this hypothetical scenario - 2) values in each row of my text file – Tamz.001 Feb 06 '17 at 23:22
  • Save your file as .csv - then you can open it in Excel. And check my answer once again, I put my comment in context. – DYZ Feb 06 '17 at 23:23
  • Yes! It works. Thank you very much-I really appreciate this. – Tamz.001 Feb 06 '17 at 23:32
0

I hope you enjoy this.

import csv


record1 = ['Chocolates', '3', 'Novels', '14', 'Pens', '4', 'Smiles', '78']
with open('box.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile)
    for item, count in zip(record1[::2], record1[1::2]):
        writer.writerow([item, count])

Reference: https://docs.python.org/2/library/csv.html#csv.writer

sangheestyle
  • 1,037
  • 2
  • 16
  • 28