Reputation: 1
i'm trying to solve the dna problem in the cs50 course and to solve it i made a small scale version wherein i made a value and the program would search the csv file for that value but for some reason it can't find it.
here's the code:
import csv
f = open("small.csv")
csv_f = list(csv.reader(f))
length=len(csv_f)
target=4
for a in range(length):
for j in range(length):
if csv_f[a][j]==target:
print("found")
i even tried using for j in range(length-1): and making target into a string through target="4" but it still didn't work can someone help me pls
Upvotes: 0
Views: 151
Reputation: 780798
Unless the file has the same number of fields as rows (which would be an incredible coincidence), you shouldn't use length
as the limit of the inner loop. It should use the length of a row as the limit, not the number of rows, i.e. for j in range(len(csv_f[a])):
.
But it's unpythonic to loop over lists using range()
. Just use for variable in list:
for row in csv_f:
for cell in row:
if cell == target:
print("found"):
You can also simplify this further by using the built-in any()
function and in
operator:
if any(target in row for row in csv_f):
print("found")
Another problem is that csv.reader()
returns all the fields as strings. So your target needs to be a string, not a number.
target = '4'
Upvotes: 0
Reputation: 420
This is because the values from the CSV file are strings. And the object you are trying to evaluate to ie target
is an integer value of 4
.
So change the target = 4
to target = "4"
Upvotes: 1
Reputation: 2399
Try this on for size.
You don't need to explicitly iterate over the range of the length, python's iterator syntax just allows you to do a for-each for rows in your row list, and then values in each row.
csv_rows = list(csv.reader(f))
for row in csv_rows:
for value in row:
if value == TARGET_VALUE:
print("found")
Upvotes: 0