我正在编写一个接受多个输入并将其保存到CSV文件的代码。到目前为止,它已保存为CSV文件,但仅保存了一条记录。
def viewstudentdetails():
name_array = list()
age_array = list()
def check_continue():
response = input('Continue? [y/n] ')
if response == 'n':
return False
elif response == 'y':
return True
else:
print('Please select a correct answer [y/n]')
return check_continue()
while(True):
std_name = input('Name: ')
age_record = input('age: ')
name_array.append(std_name)
age_array.append(age_record)
if not check_continue():
break
else:
continue
for name, age in zip(name_array, age_array):
print(name, '\t', age)
with open('studentfile.csv','a') as studentfile:
studentfileWriter=csv.writer(studentfile)
studentfileWriter.writerow([std_name, age_record])
print("Record has been written to file")
studentfile.close()
在python空闲状态下,它显示
Name: peter
age: 56
Continue? [y/n] y
Name: paul
age: 50
Continue? [y/n] n
peter 56
paul 50
使用我写的内容,在CSV文件中显示
paul 50
预期结果: 这就是它的含义:
peter 56
paul 50
答案 0 :(得分:0)
尝试
studentfileWriter.writerows(zip(name_array, age_array))