Reputation: 10179
I append a few things and in the end i have a list that looks like this
listed = ['53.02 12.36 120 33.6', 0.32 ,65 , '52 26.3 66 39.12' ,0.65 , 96]
Now i run this in a loop and at every iteration of the loop i get this list and i want to append this list to a csv with each line looking like this
53.02 12.36 120 33.6 0.32 65 52 26.3 66 39.12 0.65 96
i tried doing
listed = ' '.join(str(ele) for ele in listed)
but that gives a space for every number somewhat looking like this
5,3,.,0,2, ,1,2,.,3,6, ,0,.,2
Any ideas on how i may do this
Part of the code looks like this
f = open('Testing.csv', 'a')
writer = csv.writer(f, delimiter = '\t')
for index in range(len(dataset_train)):
for box, score, label in zip(image_boxes, image_scores, image_labels):
box = str(box).lstrip('[').rstrip(']')
listed.append(box)
listed.append(score)
listed.append(label)
listed = ' '.join(str(ele) for ele in listed)
listed = list(listed)
writer.writerow(listed)
Thanks in advance
Upvotes: 1
Views: 33
Reputation: 82815
Try:
import csv
from itertools import chain
listed = ['53.02 12.36 120 33.6', 0.32 ,65 , '52 26.3 66 39.12' ,0.65 , 96]
listed = list(chain.from_iterable([str(i).split() for i in listed])) #Flatten list
with open(filename, "w") as infile:
writer = csv.writer(infile, delimiter = '\t')
writer.writerow(listed) #Write row
Output:
53.02 12.36 120 33.6 0.32 65 52 26.3 66 39.12 0.65 96
Upvotes: 3
Reputation: 24721
You're going a bit too deep - the .join()
method works on any iterable object, including a String - which is what you're giving it. What you want is
listed = ' '.join( [str(ele) for ele in listed] )
See the inner square brackets, there, that bind [str(ele) for ele in listed]
into a single iterable object, which will then be joined.
Upvotes: 1