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.