Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python writing dictreader to csv file

I'm using python 2.4 and trying to export the value of the unix last command to a csv file. I cannot figure out how to get it to actually write each line to a csv file, any help would be appreciated!

import csv

def check(user,logfile,name):
    logfile.write('********' + name + '*********\n')
    g = subprocess.Popen(["last",user], stdout=subprocess.PIPE)
    stdout, stderr = g.communicate()
    reader = csv.DictReader(stdout.splitlines(),
                            delimiter=' ', skipinitialspace=True,
                            fieldnames=['id', 'pts', 'cpu',
                                        'day', 'month', 'date',
                                        'time', 'dash', 'off',
                                        'loggedin', 'test1', 'test2'])

    writer = csv.writer(open('dict.csv','wb'))
    for row in reader:
        writer.writerow(row)
like image 323
user1943219 Avatar asked Dec 06 '25 17:12

user1943219


1 Answers

You need to either use a csv.DictWriter() instead (with matching fieldnames), or turn the dictionary row into a sequence:

writer.row([value for key, value in sorted(row.items())])

would output the values sorted by their key, for example.

Using a DictWriter could be as simple as:

writer = csv.DictWriter(open('dict.csv','wb'), fieldnames=reader.fieldnames)

which would write the exact same fields, in the same order, as what your DictReader() class is expecting.

like image 191
Martijn Pieters Avatar answered Dec 08 '25 14:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!