过滤csv文件数据并使用Python将其保存为另一个csv文件

3bygqnnd  于 2022-12-06  发布在  Python
关注(0)|答案(1)|浏览(124)

我有一个.csv文件,其中包含如下数据:

index, name,    id
1      john     512
2      Anne     895
3      Angel    897
4      Lusia    777

所以我想通过名字结尾来过滤它们,只得到那些有元音结尾的名字。结果一定是这样的:

index, name,     id
    1      Anne     895
    2      Lusia    777

过滤后,我想将结果保存在另一个.csv文件中。我尝试了各种方法来获得正确的结果,但是,我无法做到这一点。请帮助我:(

3pvhb19x

3pvhb19x1#

先试后问有助于提高编码技能

import csv

def read_csv(filename, outfile="res.csv"):
    vowel = {"a", "e", "i", "o", "u"}
    with open(filename, 'r') as f, open(outfile, 'w', newline="") as out:
        out.write(f.readline())        # write header
        reader = csv.reader(f, delimiter=' ', skipinitialspace=True)   # space-separate and skip extra spaces
        writer = csv.writer(out)      # csv write object

        # Filter out lines that don't end with a vowel
        writer.writerows(line for line in reader if line[1][-1] in vowel) 

read_csv("a.csv", outfile="res.csv")

相关问题