I have a .csv file that has data like that:
index, name, id
1 john 512
2 Anne 895
3 Angel 897
4 Lusia 777
So I want to filter them by name endings and get names only which have vowel endings. And the result must be like that:
index, name, id
1 Anne 895
2 Lusia 777
After filtering, I want to save the result in another .csv file. I am trying various ways to get the correct result, However, I could not do that. please help me :(
CodePudding user response:
Trying before asking questions helps improve coding skills
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")