0

So I have a small script that looks pretty much:

for _ in range(3):
    with open('test.csv', 'a', newline='') as csv_file:
        writer = csv.writer(csv_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"])

sys.exit()

which basically write at this something like:

Bad

However what I would like to do is to have something like:

Done

and here basically what I can see for issue is:

  1. If there is no csv called test.csv then we create one and add the Column-1, Column-2, Column-3 only once at top.
  2. If there is already a test.csv then we don't need to add the first column Column-1, Column-2, Column-3but instead just appending into those column that is needed.

And I am not sure how I am able to do that. I would like to know how to do that.

1
  • maybe you can use pandas to do this. Commented Feb 25, 2020 at 13:16

1 Answer 1

1

CSV stands for 'Comma-separated values'. If you can't see your separated values as separated columns you should change your csv viewer delimiter settings (for Excel see here).

also you can put your for loop inside the open block to don't write your headers in every iteration

It is easier to use DictWriter instead of writer like this:

with open('names.csv', 'a', newline='') as csvfile:
    fieldnames = ['A', 'B', 'C']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for _ in range(3):
        writer.writerow({'A': 'SN', 'B': 'NAMES', 'C': 'Contribution'})
        writer.writerow({'A': '1', 'B': 'Linus Torvalds', 'C': 'Linux Kernel'})
        # and so on
Sign up to request clarification or add additional context in comments.

9 Comments

The problem here is that everything is saved into one columns as I can see through this example. Basically everything is stored at column A
Also if you throw this into a for _ in range(3): it will write the A B C everytime it opens it up aswell.
what is your software to see .csv files ?
Microsoft Excel - Im not sure if its any different?
I think you should set your delimiter character in Excel try this: extendoffice.com/documents/excel/…
|

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.