Python在CSV列中搜索值并返回字符串

2024-10-06 12:30:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python非常陌生,正在处理一个简单的项目,其中一部分应该搜索用户定义的变量,如果找到了,则根据找到的行返回一个字符串。你知道吗

我读过很多文章,这些文章引导我找到了我所拥有的代码,但是当我运行时,虽然没有出现错误,但代码会继续到下一部分。在本例中,我省略了以下部分,但如果自己运行,则在输入变量之后中断。你知道吗

import csv #CSV File Handling

#Define variables for customer file reading and appending
custData = open('custData.csv', 'a+')
custFields = ['ContactLast','ContactFirst','Company','Credit','Phone','Address','City','State','Zip']
reader = csv.DictReader(custData, delimiter=',')
writer = csv.DictWriter(custData, fieldnames=custFields)
search = ''

#Open the file
with custData:

#Display the Welcome Message and Main Menu
    mainmenugo = 'Y'
    while (mainmenugo.upper() == 'Y'):

        print ('-------------------- What would you like to do? ------------------\n'
        '--- (1) Lookup Account     (2) New Account     (quit) Shutdown ---\n'
        '------------------------------------------------------------------')
        mainmenugo = 'n' #Stop the loop from itirating forever on start
        mainmenuselect = input('Type your selection and press return : ')

        if mainmenuselect == '1':  ## Account Options Mode
            search = input('Enter the contact last name to search : ')
            for row in reader:
                if search == row['ContactLast']:
                    print (row['Company'], 'has a balance of $', row['Credit'], '. What would you like to do?')

为了清晰起见,部分代码被省略了,但这就是为什么我要按原样设置它,尽管我确信有更简单的方法。我尝试了一些不同的东西,但真的不知道从哪里开始,因为我得到了这个错误很少,但没有输出。谢谢!你知道吗


Tags: andcsvtheto代码forsearch错误
1条回答
网友
1楼 · 发布于 2024-10-06 12:30:05

我想您遇到了以下问题。^python3中的{a1}将评估用户输入有效地将用户输入1转换为整数1,然后您将尝试将其与字符串'1'进行比较。你知道吗

换言之,发生的事情如下:

In [1]: search = input('Enter the contact last name to search : ')
Enter the contact last name to search : 1

In [2]: type(search)
Out[2]: int

In [3]: search == '1'
Out[3]: False

在您的例子中,如果用户键入1if mainmenuselect == '1':比较将是错误的。你知道吗

相关问题 更多 >