Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write data to csv file in columns and rows from a list in python?

Tags:

python

list

csv

I have a list of lists and I want to write them in a csv file with columns and rows. I have tried to use writerows but it isn't what I want. An example of my list is the following:

[[1, 2], [2, 3], [4, 5]]

With this:

example = csv.writer(open('test.csv', 'wb'), delimiter=' ')
example.writerows([[1, 2], [2, 3], [4, 5]])

I get 1 2 in a cell, 2 3 in a cell, etc. And not 1 in a cell and 2 in the next cell.

I need to write this example list to a file so when I open it with Excel every element is in its own cell.

My output should be like this:

1 2
2 3
4 5

Each element in a different cell.

like image 980
IordanouGiannis Avatar asked Sep 23 '11 12:09

IordanouGiannis


People also ask

How do I add data to a CSV file in Python?

Open your CSV file in append mode Create a file object for this file. Pass the file object and a list of column names to DictWriter() You will get an object of DictWriter. Pass the dictionary as an argument to the writerow() function of DictWriter (it will add a new row to the CSV file).

What method takes a list argument and writes it to a CSV file?

A CSV file is a bounded text format which uses a comma to separate values. The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class.

How do I write a list to pandas CSV?

CSV: Import the csv module in Python, create a csv writer object, and write the list of lists to the file in using the writerows() method on the writer object. What is this? Pandas: Import the pandas library, create a Pandas DataFrame, and write the DataFrame to a file using the DataFrame method DataFrame.


1 Answers

The provided examples, using csv modules, are great! Besides, you can always simply write to a text file using formatted strings, like the following tentative example:

l = [[1, 2], [2, 3], [4, 5]]

out = open('out.csv', 'w')
for row in l:
    for column in row:
        out.write('%d;' % column)
    out.write('\n')
out.close()

I used ; as separator, because it works best with Excell (one of your requirements).

Hope it helps!

like image 73
heltonbiker Avatar answered Sep 18 '22 16:09

heltonbiker