gpt4 book ai didi

python - 将逗号分隔值的字符串列表写入 CSV

转载 作者:太空宇宙 更新时间:2023-11-04 08:36:12 26 4
gpt4 key购买 nike

我正在读取和解析平面文本文件中的行。我从该文件中获取某些值,执行一些小的格式化/转换步骤,然后吐出一个逗号分隔的字符串。到目前为止,我只是将这些字符串直接写入一个新的 csv 文件。但是,现在我正在尝试利用 csv 库来更有效地处理它。

import csv

mydata = ["This, is, a, test, row",
"This is, another test, row, my, dude",
"100, 200, 300, 400, 500"]

with open('test.csv', 'w') as target:
writer = csv.writer(target, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(mydata)

结果:

"This, is, a, test, row","This is, another test, row, my, dude","100, 200, 300, 400, 500"

这不是我想要的。而 writer.writerows(mydata) 结果是这样的:

T,h,i,s,",", ,i,s,",", ,a,",", ,t,e,s,t,",", ,r,o,w
T,h,i,s, ,i,s,",", ,a,n,o,t,h,e,r, ,t,e,s,t,",", ,r,o,w,",", ,m,y,",", ,d,u,d,e
1,0,0,",", ,2,0,0,",", ,3,0,0,",", ,4,0,0,",", ,5,0,0

据我所知,csv.writer() 正在遍历字符串列表(第一个示例)或字符串(第二个示例)。我还尝试使用 for 循环遍历 mydata 中的每个项目,但这并没有帮助 eiter。对于我的一生,我想不出最好的方法来使用 writer 来解析这些数据,以便我列表中的每个项目都对应于我的 objective-c sv 文件中的一行。将 mydata 数据存储在完全不同的数据结构中是否有意义?处理此问题的最佳方法是什么?

最佳答案

将我的数据做成二维列表,用户writer.writerows()

import csv

mydata = [['This', 'is', 'a', 'test', 'row'],
['This', 'is', 'another', 'test', 'row', 'my', 'dude'],
['100', '200', '300', '400', '500']]

with open('test.csv', 'w') as target:
writer = csv.writer(target)
writer.writerows(mydata)

writerow() 最适合用于编写单行,如标题:

import csv

myheaders = ['Header1', 'Header2', 'Header3', 'Header4', 'Header5']
mydata = [['This', 'is', 'a', 'test', 'row'],
['This', 'is', 'another', 'test', 'row', 'my', 'dude'],
['100', '200', '300', '400', '500']]

with open('test.csv', 'w') as target:
writer = csv.writer(target)
writer.writerow(myheaders)
writer.writerows(mydata)

关于python - 将逗号分隔值的字符串列表写入 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48691641/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com