You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python程序购买记录查询功能异常:无法读取customer.txt数据

问题:Python程序查询已购记录功能异常

我编写了一款Python程序,其中第一、第三功能可正常将用户购买信息保存至customer.txt文件,但第四功能在查询已购记录时,即使文件中存在对应用户名,也始终返回“User hasn't purchased anything”。以下是完整代码及运行输出示例:

完整代码

course_info = { '001': ['MS Word', '$10'], '002':['Photoshop', '$180'],
              '003':['Music player','$60'], '004': ['Photo Advance', '$110'],
              }
def menu():
 print("***************************************************\n\t\tDigiSol Online Shop for Software and Applications\n***********************************************\n1. Select this option to view all the available services in our Database\n2. Select this option to search for a service\n3. Select this option to purchase a service\n4. Select this option to view the services you have purchased in the past\n5. Select this option to Exit the program ")
 while True:
    try:
        selected_option = int(input("Please Select Options from above to proceed:"))
    except ValueError: # 处理用户输入字符串的情况
        print('Its not a number, Choose Options from above')
        continue
    # 限制用户输入在有效选项范围内
    if selected_option < 1 or selected_option > 5:
        print('Invalid Option')
    else:
        break
  return selected_option
def first_option(arg):
    print('\nPlease have a look for services and applications below:\n')                
    for key, value in arg.items():
        print(key, '-', value[0], '---', value[1])
    user_choice = input("\nThank You!\n Enter service ID to purchase or a negative number to exit: ")
    if int(user_choice) < 0:
        exit()
    elif user_choice in arg:
        print('\n' + user_choice + '. ' + arg[user_choice][0] + '   ' + arg[user_choice][1])
        while True:
            permision_to_purchase = input('\nDo you want to buy this service (Y/N)?')
            if permision_to_purchase == 'Y':
                purchase_service(arg, user_choice)
                break
            elif permision_to_purchase == 'N':
                print('Thankyou for reaching out to us\n')
                return
            else:
                print('Please select Y(Yes) or N(No)')
    else:
        print('Entered ID is not valid')

def second_option():
    while True:
        search = input('Enter name of application to see if it is available in our database:')
        searched_service = {}

        for i, j in course_info.items():
            if search in j[0].replace(" ","").lower():
                searched_service[i] = j
        if len(searched_service) == 0:
            print('Course Not Found')
        elif len(searched_service) > 1:
            print('\n',len(searched_service), 'courses have been found:\n' )
            for key, value in searched_service.items():
                print('\nCourse ID: ' + key + '\nCourse Name: '+ value[0]+'\nCourse Price: ' + value[1])
        else:
            print('\n',len(searched_service), 'course have been found:\n' )
            for key, value in searched_service.items():
                print('\nCourse ID: ' + key + '\nCourse Name: '+ value[0]+'\nCourse Price: ' + value[1])  
        while True:
            search_again = input('Do you want to search again (Y/N)?')
            if search_again == 'Y':
                break   # 退出内层循环,重新搜索
            elif search_again == 'N':
                return # 退出函数
            else:
                print('Select Y for Yes or, N for No')

def third_option(arg):
    print('\nThe available coures are listed below:\nCourse ID\t Course Name')                
    for key, value in arg.items():
        print(key, '.', value[0])
    user_choice = input("Please enter course ID to purchase or a negative number to exit: ")
    if int(user_choice) < 0:
        exit()
    elif user_choice in arg:
        print('\n' + user_choice + '. ' + arg[user_choice][0] + '   ' + arg[user_choice][1])
        while True:
            permision_to_purchase = input('\nDo you want to buy this service (Y/N)?')
            if permision_to_purchase == 'Y':
                purchase_service(arg, user_choice)
                break
            elif permision_to_purchase == 'N':
                print('Thankyou for reaching out to us\n')
                return
            else:
                print('Please select Y(Yes) or N(No)')
    else:
        print('Entered ID is not valid')


def fourth_option():
    with open("customer.txt") as searchfile:
        found = False
        while not found:
            name= input('Please enter name to search: ')
            if name == '':
                break  # 空输入退出查询循环
            for line in searchfile:
                if name in line:
                    info = line.split(',')
                    print('Hello ' + info[0] + ' you have purchase the following:\n ' + info[1] + '. ' + info[2])
                    found = True
                    break
                else:
                    print('User hasn''t purchased anything')
                    return
if __name__ == '__main__':
    while True:
        chosen_option = menu()
        if chosen_option == 1:
            first_option(course_info)
        elif chosen_option == 2:
            second_option()
        elif chosen_option == 3:
            third_option(course_info)
        elif chosen_option == 4:
            fourth_option()
        else:
            print('Goodbye')
            break

运行输出示例

*******************************************************************
        DigiSol Online Shop for Software and Applications
    *******************************************************************
    1. Select this option to view all the available services in our Database
    2. Select this option to search for a service
    3. Select this option to purchase a service
    4. Select this option to view the services you have purchased in the past
    5. Select this option to Exit the program 
    Please Select Options from above to proceed:3

    The available coures are listed below:
    Course ID    Course Name
    001 . MS Word
    002 . Photoshop
    003 . Music player
    004 . Photo Advance
    Please enter course ID to purchase or a negative number to exit: 001
    
    001. MS Word   $10
    
    Do you want to buy this service (Y/N)?Y
    Please enter your name and your credit card details:
    
    Name: Taha
    Card Number: 229493574
    Please enter a valid card number:
    Card Number: 22
    Please enter a valid card number:
    Card Number: 2294935744
    MM: 90
    YYYY:u875
*******************************************************************
        DigiSol Online Shop for Software and Applications
*******************************************************************

    1. Select this option to view all the available services in our Database
    2. Select this option to search for a service
    3. Select this option to purchase a service
    4. Select this option to view the services you have purchased in the past
    5. Select this option to Exit the program 
    Please Select Options from above to proceed:4
    Please enter name to search: Taha
    User hasnt purchased anything

问题分析与修复

问题根源

  1. 文件指针位置错误:fourth_option中文件仅打开一次,第一次遍历后指针移到文件末尾,后续查询无法读取内容。
  2. 逻辑判断错误:遍历文件时,只要第一行不匹配就直接输出错误并返回,未检查所有行。
  3. 字符串语法错误:print('User hasn''t purchased anything')的单引号未正确转义,导致语法问题。

修复后的fourth_option函数

def fourth_option():
    while True:
        name = input('Please enter name to search: ')
        if name == '':
            break  # 空输入退出查询
        found = False
        # 每次查询重新打开文件,确保指针在起始位置
        with open("customer.txt") as searchfile:
            for line in searchfile:
                line = line.strip()  # 去除换行符和首尾空格,避免匹配干扰
                if name in line:
                    info = line.split(',')
                    print(f'Hello {info[0]} you have purchased the following:\n {info[1]}. {info[2]}')
                    found = True
                    break
            # 遍历完所有行后再判断是否找到
            if not found:
                print("User hasn't purchased anything")

修复说明

  • 将文件打开操作放入查询循环内,每次查询都重新读取文件,避免指针停在末尾。
  • 遍历完所有行后再输出未找到的提示,确保检查了所有记录。
  • 修复单引号转义问题,使用f-string简化输出格式。
  • 对每行内容做strip()处理,避免换行符或空格影响匹配结果。

内容的提问来源于stack exchange,提问作者Muhammad Hamza Zaheer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 07:15:41