我得到一个文本文件BM.txt内容如下:
*A0 0194 7F9E 00 0001 B7AB A0 0194 7F9E 00 0001 B7BE A0 0194 7F9E 00 0001 B7CD A0 0194 7F9E 00 0001 B7D4*
在我的代码中: 我想用26个字符来分隔元素。26个字符的每个元素都是列表中的一个元素:
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()
列表理解的结果看起来很有希望:
['A0 0194 7F9E 00 0001 B7AB ', 'A0 0194 7F9E 00 0001 B7BE ', 'A0 0194 7F9E 00 0001 B7CD ',.....]
但是当我最终用writerow()函数编写列表时。 csv中的内容如下所示:
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,
....
真的这对我的工作来说已经足够了,但是我想知道为什么现在每个字符都是逗号分隔的?我在看帖子和csv文档,但我不明白
也许有人能回答这个问题
提前谢谢
本
您正在使用
csv.writerows
编写一个字符串列表,它将写入多个行此函数接受iterable的iterable。因此,当传递一个字符串列表时,您满足了输入的要求,但这并不是您所期望的:字符串被视为iterables,并且是按字符分割的
要写入所有数据(每行1个字符串),请使用:
(在这种情况下,
csv
模块几乎没有用处,最好在文件句柄上使用writelines
)要将所有数据写入一行,请使用
writerow
(注意最后缺少s
):尽管注释明智地建议您要根据空格再次拆分字符串,但请使用:
或者
相关问题 更多 >
编程相关推荐