如何通过Python从CSV过滤掉特定数据? [英] How to filter out specific data from a CSV via Python?

查看:653
本文介绍了如何通过Python从CSV过滤掉特定数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

People       OS      Games Owned
Anthony   Windows       120
Alissa    Windows       70
Jordan    Windows       20
Khan        Mac         47
Benny       Mac         23
Anastasia  Linux        16
McCurdy     Linux       10

我想知道,我该如何过滤出拥有超过20款游戏且没有Mac OS系统的人.我需要通过python脚本来完成它,并且在运行时,它会将其数据输出到一个单独的文件中,例如文本文件或其他内容.谢谢!

I was wondering, How would I go about filtering out people who own over 20 games, and they don't have a Mac OS System. I need it to be done via a python script, and when run, it outputs its data in a seperate file, like a text file or something. Thanks!

推荐答案

这是纯python中的解决方案,可按要求将过滤后的输出写入文本文件(csv).

Here's a solution in pure python that writes the filtered output to a textfile (csv) as requested.

import csv

with open('games.csv', 'rb') as csvfile:
    # handle header line, save it for writing to output file
    header = next(csvfile).strip("\n").split(",")
    reader = csv.reader(csvfile)
    results = filter(lambda row: row[1] != 'Mac' and int(row[2]) > 20, reader)

with open('output.csv', 'wb') as outfile:
    writer = csv.writer(outfile)
    writer.writerow(header)
    for result in results:
        writer.writerow(result)

这篇关于如何通过Python从CSV过滤掉特定数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆