Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python csv write a list to file

Tags:

python

csv

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

code:

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

for l in out_l:
    w.writerow(l)
out_f.close()

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?

like image 841
Jijo Avatar asked Dec 23 '22 23:12

Jijo


2 Answers

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.

like image 136
Mark Tolonen Avatar answered Jan 08 '23 16:01

Mark Tolonen


The csv.Writer.writerow method takes an iterable and writes the values said iterable produces into the csv fields separated by the specified delimeter:

out_f = open('test.csv', 'w')
w = csv.writer(out_f, delimiter='\t')  # set tab as delimiter

for l in out_l:  # l is string (iterable of chars!)
    w.writerow(l.split('\t'))  # split to get the correct tokens
out_f.close()

As the strings in your list already contain the necessary tabs, you could just write them directly to the file, no csv tools needed. If you have built/joined the strings in out_l manually, you can omit that step and just pass the original data structure to writerow.

like image 26
user2390182 Avatar answered Jan 08 '23 18:01

user2390182