Reputation: 79
I want to read the 1st column of each row of a CSV file in order to try and find a value. Currently I have this:
def checkForCable(idNum):
with open("test.txt") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
if row[0] == idNum:
print("matching barcode found")
return True
else:
print("barcode not on file. Adding...")
return False
But this seems to only check the first column of the first row and then stop, rather than checking all of the first columns of the n rows in the CSV file. For instance if row[0] in column 0 is not equal to the number it's searching for, then it won't proceed to check row[0] in column 1 etc. and I'm not sure why.
Upvotes: 0
Views: 3498
Reputation: 119
You can use Pandas. Pandas is very excellent in dealing with csv files.
import Pandas as pd
file = pd.read_csv('csv_file')
df = pd.DataFrame(file)
# Check if Dataframe is empty using empty attribute
if df['Columnname'].empty == True:
print('Barcode is empty')
else:
print('Barcode is not empty')
Upvotes: 0
Reputation: 882806
Regarding the code:
for row in csv_reader:
if row[0] == idNum:
print("matching barcode found")
return True
else:
print("barcode not on file. Adding...")
return False
This for
loop does indeed process every row if you let it, but you are not letting it because both your true and false parts of the if
statement return after reading the first row, effectively ignoring all the others.
What you probably need is this scheme: if you don't find it in the first row, don't immediately return false - you need to check all the other rows and return false only if it's in none of them.
In other words, something like this:
# Check ALL rows.
for row in csv_reader:
# If found in THIS row, notify success.
if row[0] == idNum:
print("matching barcode found")
return True
# If found in NO rows, notify failure.
print("barcode not on file. Adding...")
return False
Upvotes: 4