如何在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/

10-13 07:37