Dillon
Dillon

Reputation: 61

How to Stop a For Loop when a value is found from a .csv file

I'm a Network Engineer trying to learn programming using Python. I'm very new to any form of programming.

I'm trying to search for a value in column 1 from a .csv file and return the string of corresponding column. When the program is executed, it loops through all the cells, displaying the result of each cell. What I want is if a user enters a number, then it needs to search the list, once a match is found, return the next column's string. If a user entered a value that doesn't exist then return a print statement.

import csv
import sys

fileName = 'sip.csv'
READ = 'r'
WRITE = 'w'

enter_code = input('Enter The Sip Response Code: ')
with open(fileName, READ) as myXLfile:
    dataFromFile = csv.reader(myXLfile)
    for currentRow in dataFromFile:
        if enter_code == currentRow[0]:
            print("The SIP Response Code you entered is: " + enter_code)
            print("The SIP Message is:  " + currentRow[1])
            print("Meaning:  " + currentRow[2])
            break
        if enter_code != currentRow[0]:
            print("Im Sorry, I Do not have this Response Code")
    else:
        print("Thank You and Goodbye")

Result:

Enter The Sip Response Code: 200
Im Sorry, I Do not have this Response Code
Im Sorry, I Do not have this Response Code
Im Sorry, I Do not have this Response Code
Im Sorry, I Do not have this Response Code
Im Sorry, I Do not have this Response Code
Im Sorry, I Do not have this Response Code
The SIP Response Code you entered is: 200
The SIP Message is:  OK
Meaning:  The request has been successfully processed and the result of the request is transmitted in the response.

Upvotes: 2

Views: 911

Answers (2)

ASH
ASH

Reputation: 20312

Something like this should work for you.

# Select All From CSV File Where

import csv
# Asks for search criteria from user
search_parts = input("Enter search criteria:\n").split(",")
# Opens csv data file
file = csv.reader(open("C:\\your_path\\test.csv"))
# Go over each row and print it if it contains user input.
for row in file:
    if all([x in row for x in search_parts]):
        print(row)

Upvotes: 1

The_C0der
The_C0der

Reputation: 24

you mean like this:

import csv

fileName = 'sip.csv'
READ = 'r'
WRITE = 'w'
check = True

enter_code = input('Enter The Sip Response Code: ')
with open(fileName, READ) as myXLfile:
    dataFromFile = csv.reader(myXLfile, delimiter=";")
    for currentRow in dataFromFile:
        if enter_code == currentRow[0]:
            print("The SIP Response Code you entered is: " + enter_code)
            print("The SIP Message is:  " + currentRow[1])
            print("Meaning:  " + currentRow[2])
            check = False
            break
    if check:
        print("Im Sorry, I Do not have this Response Code")
    else:
        print("Thank You and Goodbye")

Upvotes: 1

Related Questions