Writing List of Strings to Excel CSV File in Python

Writing List of Strings to Excel CSV File in Python

The csv.writer writerow method takes an iterable as an argument. Your result set has to be a list (rows) of lists (columns).

csvwriter.writerow(row)

Write the row parameter to the writer’s file object, formatted according to the current dialect.

Do either:

import csv
RESULTS = [
['apple','cherry','orange','pineapple','strawberry']
]
with open('output.csv','w') as result_file:
wr = csv.writer(result_file, dialect='excel')
wr.writerows(RESULTS)

or:

import csv
RESULT = ['apple','cherry','orange','pineapple','strawberry']
with open('output.csv','w') as result_file:
wr = csv.writer(result_file, dialect='excel')
wr.writerow(RESULT)

Writing a Python list of lists to a csv file

Python's built-in CSV module can handle this easily:

import csv

with open("output.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(a)

This assumes your list is defined as a, as it is in your question. You can tweak the exact format of the output CSV via the various optional parameters to csv.writer() as documented in the library reference page linked above.

Update for Python 3

import csv

with open("out.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(a)

Python csv write a list to file

With the formatting you have in out_l, you can just write it to a file:

out_l = ['host\tuptime\tnfsserver\tnfs status\n', 'node1\t2\tnfs_host\tok\n', 'node2\t100\tnfs_host\tna\n', 'node3\t59\tnfs_host\tok\n']

with open('test.csv', 'w') as out_f:
for l in out_l:
out_f.write(l)

To properly use csv, out_l should just be lists of the columns and let the csv module do the formatting with tabs and newlines:

import csv

out_l = [['host','uptime','nfsserver','nfs status'],
['node1','2','nfs_host','ok'],
['node2','100','nfs_host','na'],
['node3','59','nfs_host','ok']]

#with open('test.csv', 'wb') as out_f: # Python 2
with open('test.csv', 'w', newline='') as out_f: # Python 3
w = csv.writer(out_f, delimiter='\t') # override for tab delimiter
w.writerows(out_l) # writerows (plural) doesn't need for loop

Note that with will automatically close the file.

See the csv documentation for the correct way to open a file for use with csv.reader or csv.writer.

Python: Write list of lists to CSV

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

How to write item in list to a row on a csv with python

Try This Out..

import csv

itemresults = ['24500', '17000', '60000', '56300', '24500', '24500', '114950', '32000', '70000', '46948', '133000', '49550', '51600', '35995', '44500', '19300', '34200', '39964', '59900', '27999', '16100', '39000', '78995', '19101', '25000', '30000', '72000', '39900', '30000', '29000', '24900', '22990', '52600', '82600', '64000', '13999', '29500', '46800', '95000', '42900', '32500', '3969', '36000', '32995', '24000', '49999.99', '37500', '34000', '47600', '43500', '28500']

filename = 'outputFile.csv'
with open(filename, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
for x in itemresults:
csvwriter.writerow([x])

Create a .csv file with values from a Python list

import csv

with open(..., 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)

Edit: this only works with python 2.x.

To make it work with python 3.x replace wb with w (see this SO answer)

with open(..., 'w', newline='') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)

string formating python to csv file

Manually increase the width of the column and you'll see the format changes.

Since you are writing a csv file (which, unlike xlsx, does not contain its own styling and formatting), it's not related to Python and there's nothing Python can do to make Excel use a specific format.

Python 3: write string list to csv file

You can use zip and join to create a new list and then write to csv :

abc=['sentence1', '-1', 'sentence2', '1', 'sentence3', '0', 'sentence4']

new=[(abc[0],)]+[(''.join(i),) for i in zip(abc[1::2],abc[2::2])]

import csv
with open('test.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
a.writerows(new)

result :

sentence1
-1sentence2
1sentence3
0sentence4


Related Topics



Leave a reply



Submit