首页 > 解决方案 > Python 索引错误:列表

问题描述

我正在尝试执行一个 python 程序来将用户输入读入文件,然后处理该文件。文件的输出如下所示:

数量|价格|项目

1|166.89|AMD 锐龙 5 3600 3.6 GHz 6 核处理器

1|149.99|华硕PRIME X570-P ATX AM4主板

2|79.99|G.Skill Ripjaws V 16 GB (2 x 8 GB) DDR4-3600 CL16 内存

1|179.97|Phanteks Eclipse P300A Mesh ATX 中塔机箱

1|140.03|威刚 XPG CORE Reactor 650 W 80+ 金牌认证全模块化 ATX 电源

1|115.98|Silicon Power A60 1 TB M.2-2280 NVME 固态硬盘

我试图执行的代码如下:

    import os
    
    def order():
        orderName = input('What would you like to call this order? :')
        print(""" Please place your order below. 
              To stop Placing your order, leave the item name empty. """)
    
        item = input("Item: ")
        price = input("Price: ")
        quantity = input("Quantity: ") #gets all the info they want to add
        print("-----------------------------------------------")
    
        with open("mypc.txt","a") as a_file:
            a_file.writelines(quantity + "|" + price + "|" + item + "\n")
            a_file.close()
            print('Order saved to ' + orderName + '.txt. Exiting Application...')
    
        with open('mypc.txt','r')as Task2:
            print('{0:<19}     {1:<19}     {2:<19}'.format("\nQuantity","Price","Item Name"))
            for row in Task2:
                row=row.strip()
                eachItem=row.split("|")
                print('{0:<19}     {1:<19}     {2:<19}'.format(eachItem[0],eachItem[1],eachItem[2]))
        print()
    
    
    
    def reciept():
        orderProcess = input('What Order would you like to Process? :')
        print("-----------------------------------------------")
        print("Going to the shops and buying eveything for you. Please hold. ")
    
    #this is the menu. this is where the user will make choices on what they do
    
    def menu():
    
    # Check if file exists
    if os.path.isfile('C:\\users\\Chandra\\Desktop\\mypc.txt')==False:
        # Create it and promptly close it, so it is in the correct location
        task1 = open('C:\\users\\Chandra\\Desktop\\mypc.txt','w')
        task1.close()
    
    # Open for read-write
    task2 = open('C:\\users\\Chandra\\Desktop\\mypc.txt','r+')
    
    # splits for new line break, making an array
    info = task2.read().split("\n")
    
    # Check to see if the file is empty
    if len(info) != 0:
        print('{0:<19}     {1:<19}     {2:<19}'.format("\nQuantity",
                                                        "Price",
                                                        "Item Name"))
        # Read each line of document
        for line in info:
            eachItem = line.split("|")
            print('{0:<19}     {1:<19}     {2:<19}'.format(eachItem[0],
                                                           eachItem[1],
                                                           eachItem[2]))
    else:
        print('You have no items listed!')
    
    print("\n")
    
    
    print(""" Welcome to the Crapple Order Management System. You can
            1. Place an Order
            2. Process an Order
            """)
    option = int(input("What would you like to do? (Select 1 or 2) : "))
    
    if option==1:
        order()
    elif option==2:
        reciept()
    
    menu()

当我运行 python 脚本时,出现以下错误:

    Quantity               Price                   Item Name
    Traceback (most recent call last):
      File "Order_Process.py", line 77, in <module>
        menu()
      File "Order_Process.py", line 58, in menu
        eachItem[1],
     **IndexError: list index out of range**.

在这方面的任何帮助将不胜感激。

谢谢。

标签: pythonread-writeindex-error

解决方案


您的数据文件中有空行。

import os


def order():
    orderName = input('What would you like to call this order? :')
    print(""" Please place your order below.
            To stop Placing your order, leave the item name empty. """)

    item = input("Item: ")
    price = input("Price: ")
    quantity = input("Quantity: ")  # gets all the info they want to add
    print("-----------------------------------------------")

    with open("mypc.txt", "a") as a_file:
        a_file.writelines(quantity + "|" + price + "|" + item + "\n")
        a_file.close()
        print('Order saved to ' + orderName +
              '.txt. Exiting Application...')

    with open('mypc.txt', 'r')as Task2:
        print('{0:<19}     {1:<19}     {2:<19}'.format(
            "\nQuantity", "Price", "Item Name"))
        for row in Task2:
            row = row.strip()
            eachItem = row.split("|")
            print('{0:<19}     {1:<19}     {2:<19}'.format(
                eachItem[0], eachItem[1], eachItem[2]))
    print()


def reciept():
    orderProcess = input('What Order would you like to Process? :')
    print("-----------------------------------------------")
    print("Going to the shops and buying eveything for you. Please hold. ")

# this is the menu. this is where the user will make choices on what they do


def menu():

    # Check if file exists
    if os.path.isfile('mypc.txt') == False:
        # Create it and promptly close it, so it is in the correct location
        task1 = open('mypc.txt', 'w')
        task1.close()

    # Open for read-write
    task2 = open('mypc.txt', 'r+')

    # splits for new line break, making an array
    info = task2.read().split("\n")

    # Check to see if the file is empty
    if len(info) != 0:
        print('{0:<19}     {1:<19}     {2:<19}'.format("\nQuantity",
                                                       "Price",
                                                       "Item Name"))
        # Read each line of document
        for line in info:
            if line.strip():

                eachItem = line.split("|")

                print('{0:<19}     {1:<19}     {2:<19}'.format(eachItem[0],
                                                               eachItem[1],
                                                               eachItem[2]))
    else:
        print('You have no items listed!')

    print("\n")

    print(""" Welcome to the Crapple Order Management System. You can
            1. Place an Order
            2. Process an Order
            """)
    option = int(input("What would you like to do? (Select 1 or 2) : "))

    if option == 1:
        order()
    elif option == 2:
        reciept()


menu()

你需要循环:

import os


def order():
    orderName = input('What would you like to call this order? :')
    print(""" Please place your order below.
            To stop Placing your order, leave the item name empty. """)

    item = input("Item: ")
    if item == '':
        return
    price = input("Price: ")
    quantity = input("Quantity: ")  # gets all the info they want to add
    print("-----------------------------------------------")

    with open("mypc.txt", "a") as a_file:
        a_file.writelines(quantity + "|" + price + "|" + item + "\n")
        a_file.close()
        print('Order saved to ' + orderName +
              '.txt. Exiting Application...')

    with open('mypc.txt', 'r')as Task2:
        print('{0:<19}     {1:<19}     {2:<19}'.format(
            "\nQuantity", "Price", "Item Name"))
        for row in Task2:
            row = row.strip()
            eachItem = row.split("|")
            print('{0:<19}     {1:<19}     {2:<19}'.format(
                eachItem[0], eachItem[1], eachItem[2]))
    print()


def reciept():
    orderProcess = input('What Order would you like to Process? :')
    print("-----------------------------------------------")
    print("Going to the shops and buying eveything for you. Please hold. ")

# this is the menu. this is where the user will make choices on what they do


def menu():

    # Check if file exists
    if os.path.isfile('mypc.txt') == False:
        # Create it and promptly close it, so it is in the correct location
        task1 = open('mypc.txt', 'w')
        task1.close()

    # Open for read-write
    task2 = open('mypc.txt', 'r+')

    # splits for new line break, making an array
    info = task2.read().split("\n")

    # Check to see if the file is empty
    if len(info) != 0:
        print('{0:<19}     {1:<19}     {2:<19}'.format("\nQuantity",
                                                       "Price",
                                                       "Item Name"))
        # Read each line of document
        for line in info:
            if line.strip():

                eachItem = line.split("|")

                print('{0:<19}     {1:<19}     {2:<19}'.format(eachItem[0],
                                                               eachItem[1],
                                                               eachItem[2]))
    else:
        print('You have no items listed!')

    print("\n")

    print(""" Welcome to the Crapple Order Management System. You can
            1. Place an Order
            2. Process an Order
            """)


def main():

    ans = ''

    while ans != '0':

        menu()
        option = input("What would you like to do? (Select 1 or 2) : ")

        if option == '1':
            order()
        elif option == '2':
            reciept()


if __name__ == "__main__":
    main()

推荐阅读