所以我正在编写一个代码,将员工信息存储为 CSV 文件,然后将其附加到 python 内的二维数组中。但是我只附加了第一行。当我输入员工姓名时,它会给出错误:索引错误:列表索引超出范围。
我有三个模块,主要:
import UserInput
import csv
import CSVManager
import os
CSVManager.createArray()
print(CSVManager.employee_storage)
UserInput.askUser()
CSVManager.findEmployee(CSVManager.employee_storage, UserInput.userInput)
用户输入:
userInput = ""
def askUser(userInput = ""):
userInput = input("Enter the name of the employee: ")
return userInput
和 CSVManager:
import csv
import os
employee_storage = [[]]
def createArray():
with open('/Users/lukabramwell/Code/employee.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
employee_storage.append(row)
print(row)
return employee_storage
def findEmployee(employee_storage, userInput):
for employee in employee_storage:
if userInput == employee[0]:
print(employee)
print("Employee name: ", employee[1])
print("Position: ", employee[2])
print("Monday Hours: ", employee[3])
print("Tuesday Hours: ", employee[4])
print("Wednesday Hours: ", employee[5])
print("Thursday Hours: ", employee[6])
print("Friday Hours: ", employee[7])
print("Saturday Hours: ", employee[8])
print("Sunday Hours: ", employee[9])
else:
print("Employee not found")
return None
我不确定 IndexError 和它只附加一行的事实是否相关。
我还是个新手,这是我第一次使用二维数组,所以我不知道先尝试什么。
您的代码中似乎有两个与您的问题相关的错误。
def createArray():
with open('/Users/lukabramwell/Code/employee.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
employee_storage.append(row)
print(row)
return employee_storage
def findEmployee(employee_storage, userInput):
if(len(employee_storage) == 0):
print("Empty employee list")
return None
for employee in employee_storage:
if userInput == employee[0]:
print(employee)
print("Employee name: ", employee[1])
print("Position: ", employee[2])
print("Monday Hours: ", employee[3])
print("Tuesday Hours: ", employee[4])
print("Wednesday Hours: ", employee[5])
print("Thursday Hours: ", employee[6])
print("Friday Hours: ", employee[7])
print("Saturday Hours: ", employee[8])
print("Sunday Hours: ", employee[9])
else:
print("Employee not found")
return None