2

In my python script I'm having a list that has the following structure:

['00:00', 'abc', '2', 'xyz']
['00:01', 'cde', '3', 'sda']

and so on. I want to write this list to csv file in a way that every element is in separate row and every string in one element is in separate column. So I want to end up with the following result in csv file:

     A     |     B    |     C    |     D
1  00:00   |    abc   |     2    |    xyz     
2  00:01   |    xyz   |     3    |    sda

Currently I have a code like this:

with open('test1.csv',mode='w',encoding='UTF-8') as result_file:
    wr = csv.writer(result_file, dialect='excel')
    for x in data:
        wr.writerow(x)

and the result I get is that every element of the list is written to column A, so it looks like this:

             A               |       
1  '00:00','abc','2','xyz'   |

How can I achieve splitting each string to separate column in csv file?

--edit

If I run the code from the first three answers I get the same result(except for the delimeter):

enter image description here

But my idea it to get 00:00 in column A, -6 in column B and so on..

6
  • Those are two lists. Can you confirm if its a list of lists or a dict of lists maybe? Commented Mar 10, 2020 at 20:46
  • Actually it's a 2 dimensional array/list. The whole structure is called data and I can get the value for each string by typing data[i][j] Commented Mar 10, 2020 at 20:51
  • 1
    Please share how data looks like? Commented Mar 10, 2020 at 20:52
  • Please provide code of an minimal reproducible example. Commented Mar 10, 2020 at 20:59
  • Sorry, the it's the list of lists, so it has a structure: [['00:00', 'abc', '2', 'xyz'] ['00:01', 'cde', '3', 'sda'] ] Commented Mar 10, 2020 at 21:01

2 Answers 2

1

How each list appears in CSV file depends on what data structure data is.

For data to be a list of lists, following code should work fine.

import csv

data = []
d1 = ['00:00', 'abc', '2', 'xyz']
d2 = ['00:01', 'cde', '3', 'sda']

data.append(d1)
data.append(d2)

with open('results_file.csv', mode='w') as results_file:
    results_writer = csv.writer(results_file, delimiter='|', quotechar='"', 
        quoting=csv.QUOTE_MINIMAL)
    results_writer.writerow(['A','B','C','D'])
    for x in data:
        results_writer.writerow(x)

results_file.csv looks like:

A|B|C|D
00:00|abc|2|xyz
00:01|cde|3|sda
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, but how can I do it if my data list has a lot of elements not only 2?
The code in answer should work for any number of list elements in data, not just for 2. I had added 2 lists in data just for an example.
0

How about a pandas approach? Nice and simple ...

import pandas as pd

data = [['00:00', 'abc', '2', 'xyz'], ['00:01', 'cde', '3', 'sda']] 
cols = ['A', 'B', 'C', 'D']

# Load data into a DataFrame.
df = pd.DataFrame(data, columns=cols)
# Write the CSV.
df.to_csv('output.csv', sep='|', index=False)

Per the docs you can change the separator using the sep parameter.

[Edited] Output:

Content of output.csv as shown from the console:

user@host ~/Desktop/so
$ cat output.csv
A|B|C|D
00:00|abc|2|xyz
00:01|cde|3|sda

3 Comments

Unfortunetly it doesnt work.. Still all of the strings are written to one column
Just opened the CSV in Libre Calc and each value is in its own column as expected. I'll revise the output because it is misleading.
@izotop - I've updated to use a pipe delimiter | for you. Just pass whatever you like into the sep parameter.

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.