简体   繁体   中英

How to write data to csv file in Python

How to write data to csv file in Python? I have csv file with data which have to be transform.

I do it in this way:

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))

id and cat have to be write to csv file. Before executed it I have csv file which looks like:

    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,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

Now, after executed my code in Python it looks like:

    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

And i want to write it to csv file with delimiter ; or , .

Does this help?

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"])

Output

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM