user12012411
user12012411

Reputation:

Scanning CSV file for specific value

I'm attempting to use Python to scan a CSV file and find a specific value in that file. I'm encountering problems with my program printing that the value isn't in the file when it is there. Any help is appreciated.

with open("sun_data.csv") as csvfile:
    readCSV = csv.reader(csvfile, delimiter=",")
    csvInfo = list(readCSV)
print(csvInfo)

x = int(input("Enter a time: "))

found = False
for i in range(len(csvInfo)):
    if csvInfo[i] == x:
        found = True
        print(str(x) + " was found in the database.")
        break 

if not found:
    print("I'm sorry, " + str(x) + " was not found in the database.")

Upvotes: 0

Views: 195

Answers (1)

shanecandoit
shanecandoit

Reputation: 621

Your code with an int cast in the comparison

with open("sun_data.csv") as csvfile:
    readCSV = csv.reader(csvfile, delimiter=",")
    csvInfo = list(readCSV)
print(csvInfo)

x = int(input("Enter a time: "))

found = False
for i in range(len(csvInfo)):
    if int(csvInfo[i]) == x:
        found = True
        print(str(x) + " was found in the database.")
        break 

if not found:
    print("I'm sorry, " + str(x) + " was not found in the database.")
    ```

Upvotes: 1

Related Questions