How to filter from a CSV file using Python Script

I have an abx.csv file with three columns. I would like to filter out data having Application as Central and write it to the 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 columns in the same .csv file (modify an existing file)

+7
source share
2 answers

You must use a different output file name. Even if you want the name to be the same, you should use some temporary name and finally rename the file. Otherwise, you first need to read the file in memory

 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) 
+7
source
 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) 
+6
source

All Articles