【问题标题】:Python IndexError: listPython 索引错误:列表
【发布时间】:2020-10-26 02:16:56
【问题描述】:

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

数量|价格|项目

1|166.89|AMD Ryzen 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+ Gold 认证全模块化 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**.

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

谢谢。

【问题讨论】:

  • 这意味着列表中没有那么多项目
  • 是的,Derek.. 我正在尝试使用详细信息创建文件,然后再进行处理。那么,我的代码中是否有问题导致此问题?我想问用户他在 menu() 中的选项,然后如果他选择选项 1.. 将用户输入到一个文件中,直到他输入一个空值并将其保存为 mypc.txt 文件。
  • 似乎您正在通过'|' 吐出一行来生成 eachItem,如果结果列表只有 1 个元素长,那么问题将是该行中没有该字符跨度>
  • 当你在 'mypc.txt' 中写一行时,你添加了一个空行,所以当你打开它进行阅读时,你会得到第一行的信息和第二个空行。只需从 info 中删除空行。
  • @Gray_Rhino - 感谢您的回复。您能指出代码中的更改吗?那会很有帮助的。

标签: python read-write index-error


【解决方案1】:

您的数据文件中有空行。

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()

【讨论】:

  • 感谢您的代码。但是代码只输入一次然后退出。我需要代码来接受这些值,直到我在项目中输入一个空值。你能帮我改一下代码吗?谢谢。
  • 需要在main函数中写一个循环。当你读取一个项目名称时,检查它是否为空并从函数中返回。否则,请阅读其他字段。
  • 你打开文件这么多次。你应该清理代码。所以它会在开头打开文件。将文件读取移出菜单功能。
猜你喜欢
  • 2014-08-11
  • 1970-01-01
  • 2016-07-31
  • 2021-05-12
  • 1970-01-01
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多