Search code examples
pythoncsvfile-writing

How do I create a csv file using python?


I have 7 separate parameters that I have lists for. Let's call them A, B, C, D, E, F, and G.

All of these parameters will be lists of numbers.

I need to make a csv file that is in this format:

A______B_______C_______D............F

a[0]____b[0]_____c[0]_____d[0].........f[0]

a[1]____b[1]_____c[1]_____d[1].........f[1]

a[2]____b[2]_____c[2]_____d[2].........f[2]

a[3]____b[3]_____c[3]_____d[3].........f[3]

...................................................................

a[-1]___b[-1]_____c[-1]____d[-1]........f[-1]

Unfortunately, these lists won't be a constant length, but will always have the same number of values as each other, so I can't hardcode this.

I did some reading and found that python has an integrated csv library, but I couldn't figure out how to use it.

So how would I use python to create a csv file with the layout above?

Thanks in advance!


Solution

  • Using Python3, you can do something like this:

    import csv
    
    with open('name.csv', 'w') as csvfile:
        writer = csv.writer(csvfile)
        # header
        writer.writerow(['A', 'B', ..., 'F'])
        for i in range(len(A)):
            writer.writerow([A[i], B[i], ..., F[i]])