Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Filter from CSV file using Python Script

Tags:

python

csv

filter

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)

like image 478
user1386541 Avatar asked May 10 '12 08:05

user1386541


2 Answers

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)
like image 154
mshsayem Avatar answered Sep 20 '22 18:09

mshsayem


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)
like image 43
San4ez Avatar answered Sep 20 '22 18:09

San4ez