user1386541
user1386541

Reputation: 181

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)

Upvotes: 18

Views: 77251

Answers (2)

San4ez
San4ez

Reputation: 8251

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') as fin, open ('outfile','w') as fout:
    writer = csv.writer(fout, delimiter=' ')            
    for row in csv.reader(fin, delimiter=' '):
        if row[2] == 'Central':
             writer.writerow(row)

Upvotes: 16

mshsayem
mshsayem

Reputation: 18038

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)

Upvotes: 20

Related Questions