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