0

I am not familiar with how to export the list to the csv in python. Here is code for one list:

import csv
X = ([1,2,3],[7,8,9])
Y = ([4,5,6],[3,4,5])
for x in range(0,2,1):
    csvfile = "C:/Temp/aaa.csv"
    with open(csvfile, "w") as output:
        writer = csv.writer(output, lineterminator='\n')
        for val in x[0]:
            writer.writerow([val])

And I want to the result:

enter image description here

Then how to modify the code(the main problem is how to change the column?)

0

3 Answers 3

1

To output multiple columns you can use zip() like:

Code:

import csv

x0 = [1, 2, 3]
y0 = [4, 5, 6]
x2 = [7, 8, 9]
y2 = [3, 4, 5]
csvfile = "aaa.csv"
with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerow(['x=0', None, None, 'x=2'])
    writer.writerow(['x', 'y', None, 'x', 'y'])
    for val in zip(x0, y0, [None] * len(x0), x2, y2):
        writer.writerow(val)

Results:

x=0,,,x=2
x,y,,x,y
1,4,,7,3
2,5,,8,4
3,6,,9,5
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, that works, but could we write this in a loop for x= 0,2...., i mean update writing the CSV file as loop runs
The answer to your questions is YES. But I do not understand your questions as to the specifics.
I mean when x=0, we write the first two columns(x0,y0) and when x=2, we add the next two columns(x2,y2) in the same CSV, etc. In your code, you already knew the number of columns.
But your variables are named x0 and x2. This is extremely bad practice if you want to iterate over them as a group. How about using a dict so that you can properly iterate? Other than that does this answer answer the question you asked?
ok, I just change the code, could help me modify the code for loop?
|
0

You could try:

with open('file.csv') as fin:
    reader = csv.reader(fin)
    [fout.write(r[0],r[1]) for r in reader]

If you need further help, leave a comment.

Comments

0

When dealing with csv files you should really just use Pandas. Put your header and data into a dataframe, and then use the .to_csv method on that dataframe. Csv can get tricky when you have strings that contain commas, etc...

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html

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.