Trying to learn
Trying to learn

Reputation: 43

Locating text within a .csv in Python

Within a .csv document I have is the line:

AAPL,"Apple Inc.","163.03","$827.22B","1980","Technology","Computer Manufacturing","https://www.nasdaq.com/symbol/aapl",

After beginning my program it prompts the user for the .csv filepath as well as the stock ticker to search for. In this instance I am searching for AAPL.

import csv
from tkinter import
import tkinter.simpledialog

root = Tk()
w = Label(root, text="Stock locator")
w.pack()

nasdaqDatabase = tkinter.simpledialog.askstring("NASDAQ Database", "Please input your NASDAQ database csv directory") 
webUrlTest = tkinter.simpledialog.askstring("Stock Ticker Input", "Input a stock ticker") 

with open(nasdaqDatabase, "r") as f:
    csvreader = csv.reader(f, delimiter=",")
    for row in csvreader:
        if webUrlTest in row[0]:
            print(webUrlTest + ' has been located in the NASDAQ')
        else:
            print('not found')
            quit()

The output when the code is run searching for AAPL is the following:

not found

Process finished with exit code 0

Why would it not return that AAPL has been found? Where am I going wrong in this example? Thank you for the assistance!

Upvotes: 0

Views: 59

Answers (2)

nchen24
nchen24

Reputation: 502

for row in csvreader:
    if webUrlTest in row[0]:
        print(webUrlTest + ' has been located in the NASDAQ')
    else:
        print('not found')
        quit()

This will check the first row, and quit() if it's not what you're looking for. Surely you want something more like this:

found = False
for row in csvreader:
    if webUrlTest in row[0]:
        print(webUrlTest + ' has been located in the NASDAQ')
        found = True
if not found:
    print('not found')
    quit()

You could also wrap it in a function to avoid the slightly kludgey found flag ;)

Upvotes: 2

ddg
ddg

Reputation: 1098

You code quits if any row is not AAPL. What you intented to express with the else statement is

for row in csvreader:
    if webUrlTest in row[0]:
        print(webUrlTest + ' has been located in the NASDAQ')
        break
else:
    print('not found')

Some people have strong objections to for ... else statements. They would suggest this approach

found = False
for row in csvreader:
    if webUrlTest in row[0]:
        print(webUrlTest + ' has been located in the NASDAQ')
        found = True
        break
if not found:
    print('not found')

For catching this kind of error by yourself, I would strongly recommend using a python debugger, so you can step through and watch the execution. There's a built in debugger, also most IDEs (eg PyCharm) have debuggers with nice interfaces. You can search for tutorials on how to use a debugger.

Upvotes: 0

Related Questions