gpt4 book ai didi

python - 如何在Python中将数据写入csv文件

转载 作者:行者123 更新时间:2023-12-01 06:32:48 26 4
gpt4 key购买 nike

如何用Python将数据写入csv文件?我有 csv 文件,其中包含必须转换的数据。

我这样做:

import csv

with open('bookcat.csv') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
if row:
id = row[0].strip()
categories = row[1:]
for cat in categories:
cat = cat.strip()
if cat:
print("%s\t%s" % (id, cat))

idcat 必须写入 csv 文件。在执行之前,我有 csv 文件,如下所示:

    1,,,,,,,,201,202,,204,,206,207,208,,301,,,,,,,,,,,,,,,,,,,,,,,,605,606,,
2,,,,,,,,201,,,204,205,,,,209,301,,,304,,402,,,405,,,,,,,,,,,,,,,604,,,,
3,,,,,,,,201,,,,,,,,,,,,,,,,,,,,,,,506,,,,,,,,,,,,,
4,,,,,,,,,,,204,,206,,208,209,,,,,,,,,,,,,,,,,,,,,,,,,,,,
5,,,,,,,,201,,,204,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

现在,在 Python 中执行我的代码后,它看起来像:

    1   201
1 202
1 204
1 206
1 207
1 208
1 301
1 605
1 606
2 201
2 204
2 205
2 209
2 301
2 304

我想将其写入带有分隔符的 csv 文件;或,。

最佳答案

这有帮助吗?

import csv
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["SN", "Name", "Contribution"])
writer.writerow([1, "Linus Torvalds", "Linux Kernel"])
writer.writerow([2, "Tim Berners-Lee", "World Wide Web"])
writer.writerow([3, "Guido van Rossum", "Python Programming"])

输出

SN,Name,Contribution
1,Linus Torvalds,Linux Kernel
2,Tim Berners-Lee,World Wide Web
3,Guido van Rossum,Python Programming

关于python - 如何在Python中将数据写入csv文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59812189/

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