Python 如何将多个记录保存到csv文件?
我正在编写一个接受多个输入并将其保存到CSV文件的代码。到目前为止,它保存为CSV文件,但只保存一条记录Python 如何将多个记录保存到csv文件?,python,python-3.x,Python,Python 3.x,我正在编写一个接受多个输入并将其保存到CSV文件的代码。到目前为止,它保存为CSV文件,但只保存一条记录 def viewstudentdetails(): name_array = list() age_array = list() def check_continue(): response = input('Continue? [y/n] ') if response == 'n': return Fals
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()
在pythonidle中,它显示
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(名称数组、年龄数组))
试试看
studentfileWriter.writerows(zip(名称数组、年龄数组))
在打开文件之前,您正在迭代列表,因此只需使用块将迭代移动到中,并相应地更改writerow
。进一步说,studentfileWriter.writerow([std_name,age_record])
您正在向文件写入最后一次输入,不是列表中的元素在打开文件之前,您正在迭代列表,因此只需将迭代移动到带有
块的中,并相应地更改writerow
。进一步说,studentfileWriter.writerow([std_name,age_record])
您正在向文件写入最后一次输入,不是列表中的元素