Python:如何正确分割字符串以保存为csv格式?



我试图将字符串保存为csv格式。字符串看起来像这样,一行以'n'分隔,:

12,12,11,13,11,12
21,15,21,23,41,26
34,16,46,17,21,15
44,17,22,39,10,13

等等。此外,我有一个手动编写的标题列表,如

['A', 'B', 'C', 'D', 'E', 'F']

当我尝试用csv写入器写这个时,

with open('output.csv', 'w', newline='') as csvwriter:
writer = csv.writer(csvwriter, dialect='excel')
writer.writerow(header) # write header
for r in output.splitlines():
writer.writerows(r)
csvwriter.close()

但是当我查找输出文件时,

A,B,C,D,E,F
1
2
","
1
2
","
1
1
","
... (and so on)

为什么会发生这种情况,我该如何解决这个问题?谢谢你的帮助。

如果你的字符串是这样的:

string = '''12,12,11,13,11,12
21,15,21,23,41,26
34,16,46,17,21,15
44,17,22,39,10,13'''
headers = ['A', 'B', 'C', 'D', 'E', 'F']

没有任何库:

with open('untitled.txt', 'w') as f:
f.write(','.join(headers)+'n')
for line in string:
f.write(line)

你可以把它变成一个pandas csv文件,然后保存:

import pandas as pd
data = []
for i in string.split('n'):
data.append(i.split(','))
csv = pd.DataFrame(data=data, columns=headers)
csv.to_csv('path_to_save', index=False)

相关内容

  • 没有找到相关文章

最新更新