1

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

19
  • Please don’t share code/data as images. Can you explain what the issue is? Have you read the csv docs? Commented Jan 19, 2020 at 16:54
  • hello, this image shosw how to data should looks like in the csv file which I have to create. Commented Jan 19, 2020 at 17:15
  • Right, yes, I’m not sure how that relates to my comment though. Commented Jan 19, 2020 at 17:21
  • Ok, I edited my question. It is better now? My question is:how to save this data to a csv file? Commented Jan 19, 2020 at 17:23
  • I was looking for something more specific. What have you tried? Which part are you struggling with? Commented Jan 19, 2020 at 17:24

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.