python - 如何在循环中写入csv文件

时间:2015-06-17 23:26:50

标签: python

我有这段代码执行循环:

for i in os.listdir(os.getcwd()):
   if i.endswith(".gz"):
        myfilename=i
        getHum=int(subprocess.check_output('''zcat %s |  awk 'BEGIN {FS=";"};{print $6}' | grep -i 'hummer' | wc -l''' % myfilename, shell=True))
        getBMW=int(subprocess.check_output('''zcat %s |  awk 'BEGIN {FS=";"};{print $6}' | grep -i 'bmw' | wc -l''' % myfilename, shell=True))
        getAudi=int(subprocess.check_output('''zcat %s |  awk 'BEGIN {FS=";"};{print $6}' | grep -i 'audi' | wc -l''' % myfilename, shell=True))

现在,我正在尝试修改它,因此我将输出写入逗号sep csv文件。 如何遍历每个文件并将提取的内容写入csv文件?感谢。

1 个答案:

答案 0 :(得分:2)

我觉得这样的事情可以做你想做的事情:

def get_brand_count(filename, brand):
    return int(subprocess.check_output('''zcat %s |  '''
                                       '''awk 'BEGIN {FS=";"};{print $6}' | '''
                                       '''grep -i %r | wc -l''' %
                                       (filename, brand), shell=True))

brands = 'hummer', 'bmw', 'audi'
with open('results.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(brands)  # csv header row (if desired)
    for myfilename in glob.iglob('*.gz'):
        csvwriter.writerow([get_brand_count(myfilename, brand)
                                for brand in brands])