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.
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).
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With