python - 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**.
在这方面的任何帮助将不胜感激。
谢谢。
解决方案
您的数据文件中有空行。
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()
推荐阅读
- angular - Angular 7 路由错误 base-href 被附加到路径
- c - 未初始化的全局变量对可执行文件大小的影响
- php - 我的表单中有 3 个日期范围选择器我想存储 00-00-0000 00-00-0000
- c - 具有无限多(未命名)参数的函数 - 如何正确访问这些参数?
- reactjs - 构建 react-app 的意外结果
- ios - 如何在 Swift 中使用可解码?
- c++ - 如何在 iOS 上跟踪 C++ 内存分配?
- c# - 需要 C# datagrid 视图中 Quantity 列的默认值的帮助,它应该是可变的
- android-studio - Android Studio 3.2.1 找不到资源错误
- javascript - sqlite3 插入或更新