如何仅将包含特定字符串(在CSV文件中)的行另存为单独的CSV文件?

时间:2015-12-01 06:48:23

标签: android python file parsing csv

我想只将包含特定字符串的行(在CSV文件中)保存为单独的CSV文件?

考虑以下文件:

foo,bar,zig,zag
zog,bar,zag,zag
qux,zig,zag,zag
quuux,bar,zag,zag

过滤为条形时,结果应为单独的CSV文件:

foo,bar,zig,zag
zog,bar,zag,zag
quuux,bar,zag,zag

实现这一目标的最有效方法是什么?是否有代码可以执行此操作,因为我需要为大约200个名称执行此操作,例如" bar"。

1 个答案:

答案 0 :(得分:1)

您可以按特定列过滤每一行(假设它始终是同一列):

import csv

names = ['bar', 'foo', 'foobar']
data = []

# read data
with open('all.csv', 'r') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',')
    for row in spamreader:
        if row[1] in names:
            data.append(row)

# maybe some more processing
# ...

# write back data that meets criteria
with open('bar.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    spamwriter.writerows(data)