简体   繁体   English

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

[英]How to save only lines containing a particular String (in a CSV file) as a separate CSV file?

I want to save only lines containing a particular String (in a CSV file) as a separate CSV file? 我只想将包含特定字符串(在CSV文件中)的行另存为单独的CSV文件?

Consider the following file: 考虑以下文件:

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

When filtered for bar, the result should be a separate CSV file: 过滤为条形时,结果应为单独的CSV文件:

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

What's the most efficient way to achieve this? 最有效的方法是什么? Is there code to do this, as I need to do it for about 200 such names as "bar". 有没有执行此操作的代码,因为我需要为大约200个诸如“ bar”之类的名称执行此操作。

You could just filter each row by a certain column (assuming it's always the same column): 您可以按某一列过滤每一行(假设它始终是同一列):

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM