1

This is csv file

name,country,code
Georgina,Saint Helena,ET
Brooks,Austria,LR
Rosaline,Peru,DZ

How to get a particular row data without looping the whole csv file?

Looking for following syntax: If searchName exist in csv, extract the data

searchName = 'Brooks'
with open('name.csv', 'r') as file:
  reader = csv.DictReader(file)
  for row in reader:
    if (row['name']) == searchName :
      print(row['name'] + ' >> ' + row['country'])

Thanks

Update panda solution for those who interested

import pandas as pd

df = pd.read_csv('a.csv')
select_row = df.loc[df['name'] == 'Brooks']
if select_row.empty:
    print('No records')
else:
    print('Print Record')
    print(select_row.country)
5
  • Can you please clarify what A is in if(row['name'] == A: ? Commented May 16, 2020 at 8:09
  • should be if (row['name']) == searchName: Commented May 16, 2020 at 8:13
  • why don't you use pandas? Commented May 16, 2020 at 8:17
  • Are you looking only for the first match of your searchName? Or all matches? Commented May 16, 2020 at 8:55
  • By design, the actual csv have unique names. The first match should be OK Commented May 16, 2020 at 8:57

3 Answers 3

1

Get first instance

search_name = 'Brooks'
with open('name.csv', 'r') as file: 
    output = re.search(f'{search_name}.*', file.read())

row = output.group().split(',')
print(row[0], '>>' ,row[1])

Get all instances

search_name = 'Brooks'
with open('name.csv', 'r') as file: 
    output = re.findall(f'{search_name}.*', file.read())

for row in output: 
    items = row.split(',')
    print(items[0], '>>' ,items[1])

Using DataFrames

import pandas as pd 

search_name = 'Brooks'
df = pd.read_csv('name.csv')
output = df[df.name == search_name].iloc[0]
print(output['name'], '>>', output['country'])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for alternative solution. use of column name ( row['name'] ) is preferred because column numbers might change from time to time. Will study on how to use panda
I posted a pandas example at the bottom. This will retrieve the first matching instance.
1

You could try using pandas and make your life easier, try something like this :

import pandas as pd

df = pd.read_csv('name.csv')

if df.iloc[5, 6]:
# execute condition
else
# execute another condition

I have given you an outline,you can try to use this and come up with a solution for your issue.

2 Comments

I think you want a python script other than using pandas DataFrame and get the value of a single row without iterating the rows. I don't think so to get the value without looping each row.
panda solution for those who interested import pandas as pd df = pd.read_csv('a.csv') select_row = df.loc[df['name'] == 'Brooks'] if select_row.empty: print('No records') else: print('Print Record') print(select_row.country)
1

Although dataframe seems to be the best option, if you treat the csv as a simple text file, This should help you:

searchName = 'Brooks'
with open('name.csv', 'r') as f:
    foo = f.read()

items=re.findall(f"{searchName}.*$",foo,re.MULTILINE)

print(items)

Output:

['Brooks,Austria,LR']

Comments

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.