Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

searching for a value in csv and returning the row multiple times

Tags:

python

csv

excel

i'm a noob trying to learn python,

i am trying to write a script for a CSV file that has 30,000 rows of data.

i would like to look through every row for a number in a column and return the row every time it finds that number.

i have searched and tried many different suggestion and they don't seem to do what i need it to can anyone help me, if i'm not making sense please let me know.

here is what i have so far and it is only returning to headers:

    import csv

with open("test.csv", "r") as input, open ("result.txt","w") as result:
          testfilereader = csv.DictReader(input) 
          Age = 23
          fieldnames = testfilereader.fieldnames
          testfilewriter = csv.DictWriter(result, fieldnames, delimiter=',',)
          testfilewriter.writeheader()      
          for row in testfilereader:
                 for field in row:
                        if field == Age:
                             testfilewriter(row)


input.close

thanks all

like image 839
scott.turner Avatar asked Oct 17 '25 14:10

scott.turner


1 Answers

You can use Pandas as follows:

csv file:

Id,Name,Age
1,John,30
2,Alex,20
3,Albert,30
4,Richard,30
5,Mariah,30

python:

import pandas as pd

df = pd.read_csv("ex.csv", sep = ",")
print df[df["Age"] == 30] 

   Id     Name  Age
0   1     John   30
2   3   Albert   30
3   4  Richard   30
4   5   Mariah   30
like image 138
Carles Mitjans Avatar answered Oct 19 '25 04:10

Carles Mitjans