简体   繁体   中英

How to Filter from CSV file using Python Script

I have abx.csv file having three columns. I would like to filter the data which is having Application as Central and write it in same .csv file

User ID   Name        Application  

001       Ajohns      ABI
002       Fjerry      Central
900       Xknight     RFC
300       JollK       QDI
078       Demik       Central

I need to write User ID,Name,Apllication in three column in same .csv file (modifying the existing file)

import csv
reader = csv.reader(open(r"abx.csv"),delimiter=' ')
filtered = filter(lambda p: 'Central' == p[2], reader)
csv.writer(open(r"abx.csv",'w'),delimiter=' ').writerows(filtered)

You should use different output filename. Even if you want the name to be the same, you should use some temporary name and finally rename file. Otherwise you have to read file to memory at first

import csv
with open('infile','r'), open ('outfile','w') as fin, fout:
    writer = csv.writer(fout, delimiter=' ')            
    for row in csv.reader(fin, delimiter=' '):
        if row[2] == 'Central':
             writer.writerow(row)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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