python - 如何将多条记录保存到 csv 文件?
问题描述
我正在编写一个接受多个输入并将它们保存到 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 idle 中,它显示
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
解决方案
尝试
studentfileWriter.writerows(zip(name_array, age_array))