繁体   English   中英

如何将多个记录保存到csv文件中?

[英]How can i save Multiple records to a csv file?

我正在编写一个接受多个输入并将其保存到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

尝试

studentfileWriter.writerows(zip(name_array, age_array))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM