这是实际上将我的五个列表中的值导出到 .csv 文件的脚本:
def exportEmployee(): # I moved the indentation over for clarity
import csv
with open('exportemployee.csv', 'w') as csvfile:
export_employee = csv.writer(csvfile)
export_employee.writerows([employeeName_List, employeeSSN_List, employeePhone_List,employeeEmail_List, employeeSalary_List])
print("Employees' record exported to file.\n\n")
功能性起作用了,但是在执行相反操作(导入)时遇到了问题:
def importEmployee(): # I moved the indentation over for clarity
import csv
f = open('importemployee.csv')
data = []
for line in f:
data_line = line.rstrip().split(',')
data.append(data_line)
employeeName_List = data[0]
employeeSSN_List = data[1]
employeePhone_List = data[2]
employeeEmail_List = data[3]
employeeSalary_List = data[4]
# print(*employeeName_List, sep = ', ')
我在导入功能之外打印列表,列表为空白。但是,如果我在函数中使用print(*employeeName_List, sep = ', ')
打印列表,它将返回列表中的值。
我在这里想念什么?
答案 0 :(得分:0)
您的employeeXXX_List
变量是局部变量,它们仅存在于函数范围内。如果要在外面使用它们,则必须将它们退回-最简单的方法是仅返回data
,如果需要不同的列表,则最终在以后将其解压缩:
def importEmployee():
data = []
# this makes sure your file will be closed
with open('importemployee.csv') as f:
for line in f:
# using csv.reader would be safer...
data_line = line.rstrip().split(',')
data.append(data_line)
return data
data = importEmployee()
employeeName_List = data[0]
employeeSSN_List = data[1]
employeePhone_List = data[2]
employeeEmail_List = data[3]
employeeSalary_List = data[4]
请注意,以这种方式(在csv级别和Python代码中)构造数据是一个巨大设计错误,因为您依赖于列表中的项目位置保持一致,这并不相同保证(如果您的列表类型将您的数据混合在一起,则一名员工将收到另一名员工的电子邮件或SSN等)。正确的数据结构是(name, ssn, phone, email, salary)
元组的列表,它也与预期的csv结构匹配,其中column是字段,行是值(第1列是“ name”字段,第2列是“ ssn”字段等)。