-1

Lets say I have a CSV file that looks like this:

name,country,email
john,US,john@fake.com
brad,UK,brad@fake.com
James,US,james@fake.com

I want to search for any county that equals US and if its exists, then print their email address. How would I do this in python without using pandas?

devops_jmo
  • 11
  • 2

2 Answers2

0

You can do something like:

with open('file.csv', 'r') as f: 
    f.readline()
    for line in f: 
        data = line.strip().split(',')

Then you can access the stuff inside of data to get what you need.

Andrew Wei
  • 870
  • 1
  • 7
  • 12
-1

So to read an CSV as dataframe you need:

import pandas as pd
df = pd.read_csv("filename.csv") 

Next, I will generate a dummy df and show you how to get the US users and then print their emails in a list:

df= pd.DataFrame({"Name":['jhon','brad','james'], "Country":['US','UK','US'], 
"email":['john@fake.com','brad@fake.com','james@fake.com']})
US_USERS = df.loc[df['Country']=='US']
US_emails = df['email'].tolist()
print(US_USERS)
print(US_emails)

you should get:

    Name Country           email
0   jhon      US   john@fake.com
2  james      US  james@fake.com

['john@fake.com', 'brad@fake.com', 'james@fake.com']
Mohamed Afify
  • 160
  • 1
  • 8