SuperSpamTube
SuperSpamTube

Reputation: 107

Write list elements to fields in a csv-file in python using the csv modul

i got a textfile BM.txt the content looks like this:

*A0 0194 7F9E 00 0001 B7AB A0 0194 7F9E 00 0001 B7BE A0 0194 7F9E 00 0001  B7CD A0 0194 7F9E 00 0001 B7D4*

In my code: I want to seperate elements by 26 charackters. Each element of 26 chars is a element in the list:

import csv #import csv modul using writerows function 
#csv docs https://docs.python.org/3/library/csv.html

#open the file with the string element to seperate bm elements.
    file = open("BM.txt", "r")
    c = file.read()
#list comp that seperates the elements by 26 charackters each
    neue_liste = [c[i:i+26] for i in range(0, len(c), 26)] 

#creating a new file with the bm elements as comma seperated values
    with open('briefmarken.csv', 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerows(neue_liste)
    file.close()

The result of the list comprehension looks promising:

['A0 0194 7F9E 00 0001 B7AB ', 'A0 0194 7F9E 00 0001 B7BE ', 'A0 0194 7F9E 00 0001 B7CD ',.....]

But when i finally write the list with the writerow()-function. The content in the csv looks like this:

A,0, ,0,1,9,4, ,7,F,9,E, ,0,0, ,0,0,0,1, ,B,7,A,B, 
A,0, ,0,1,9,4, ,7,F,9,E, ,0,0, ,0,0,0,1, ,B,7,B,E, 
A,0, ,0,1,9,4, ,7,F,9,E, ,0,0, ,0,0,0,1, ,B,7,C,D, 
....

Really this is good enough for my work but i wonder why every charackter is now comma seperated? And iam looking at the posts and the csv docs but i dont get it.

Maybe someone can answert this question.

Thanks in advance

Ben

Upvotes: 1

Views: 78

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

you're writing a list of strings using csv.writerows, which writes several rows.

This function accepts an iterable of iterables. So when passing a list of strings, you're satisfying the input but it's not what you're expecting: the strings are seen as iterables, and are split character by character.

To write all your data, 1 string per row, use:

writer.writerows([x] for x in neue_liste)

(well, csv module is hardly useful in that case, better use writelines on a file handle)

To write all your data in 1 row use writerow (note the lack of s in the end):

writer.writerow(neue_liste)

although comments suggest wisely that you want to split your strings again according to spaces, then use:

writer.writerows(x.split() for x in neue_liste)

or

writer.writerows(map(str.split,neue_liste))

Upvotes: 3

Related Questions