3

我正在使用 python 2.4 并尝试将 unix last 命令的值导出到 csv 文件。我不知道如何让它实际将每一行写入 csv 文件,任何帮助将不胜感激!

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

1 回答 1

5

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.

于 2013-05-28T14:41:52.807 回答