我有一個 .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 檔案中。我正在嘗試各種方法來獲得正確的結果,但是,我做不到。請幫我 :(
uj5u.com熱心網友回復:
在提問之前嘗試有助于提高編碼技能
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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/515550.html
上一篇:將csv檔案轉換為所需的輸出
下一篇:如何過濾資料集中的大寫字母
