Home > Software design >  python - newbie problem with for loop and conditionals
python - newbie problem with for loop and conditionals

Time:04-27

I'm having problems with for and conditionals in my code.

I' trying to do a search inside a .csv and working with pandaspd. I have something similar to this

for i in csv_row:
    if csv_row == 'hello':
       print('FOUND')

So what I'm trying is to find in an specific row the word "hello" and then to print FOUND. But it doesn't work. But if I change the == to != it will print FOUND for each row in the .csv file.

What can I do? I couldn't find help searching online.

Thanks!

CodePudding user response:

!= means not equal, that's why you get "FOUND" every time.

You could do this:

import csv
with open(r'path/samplecsv.csv') as file_obj:
    reader_obj = csv.reader(file_obj)
    for row in reader_obj:
        if row == "hello":
           print("FOUND")

CodePudding user response:

You need to refer i instead of csv_row.

for i in csv_row:
    if i == 'hello':
       print('FOUND')

if csv_row is a text file or whatever.

f= open("csv_row.csv", "r")

for i in f.readlines():
    if 'hello' in i:
       print('FOUND')

f.close()

edit: As you are using pandas, you can do something like this.

import pandas as pd

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

# get each row data as a list
for row in df.iterrows():
    # iterate through list and find pecific value  
    for i in row:
         if 'hello' in str(i):
             print('found', i)

You can edit the code as you want.

  • Related