Jijo Jijo - 6 months ago 33
Python Question

Python csv write a list to file

I am writing a script to write a list with tab separated as below to a csv file. But i am not getting proper output on this.

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']


out_f = open('test.csv', 'w')
w = csv.writer(out_f)

for l in out_l:

The output csv file reads as below.

h,o,s,t, ,s,s,h, , , , , ,s,u,d,o,_,h,o,s,t, , , , , , , ,n,f,s,"
"1,9,2,.,1,6,8,.,1,2,2,.,2,0,1, ,o,k, ,n,f,s,h,o,s,t, ,o,k,"
"1,9,2,.,1,6,8,.,1,2,2,.,2,0,2, ,f,a,i,l,e,d, ,n,a, ,n,a,"
"1,9,2,.,1,6,8,.,1,2,2,.,2,0,3, ,o,k, ,n,f,s,h,o,s,t, ,s,h,o,w,m,o,u,n,t, ,f,a,i,l,e,d,"


Also I have checked the csv.writer option like delimiter, dialect=excel, but no luck.
Can some one help to format the output?


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:

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

import csv

out_l = [['host','uptime','nfsserver','nfs status'],

#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.