18

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)

2 Answers 2

20
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)
Sign up to request clarification or add additional context in comments.

1 Comment

This will not write column names
16

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)

11 Comments

You don't need to nest those with context managers on separate indent levels. Instead, do with open('infile','r), open ('outfile','w') as fin, fout:.
Actually, also note that you're going to need to specify some dialect parameters here. delimiter=" " at a minimum.
I thought OP could do something by himself
If he copies and pastes your code, it won't work, and he'll have little idea why. You could at least include a disclaimer that he's going to need to adjust for space-separated files - a pointer to the csv module documentation wouldn't hurt. As a bonus, this introduces the OP to the habit of reading the documentation - win-win!
This doesn't really work, it should be with open('infile','r') as fin, open ('outfile','w') as fout:
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.