Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将多个记录保存到csv文件?_Python_Python 3.x - Fatal编程技术网

Python 如何将多个记录保存到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

我正在编写一个接受多个输入并将其保存到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()
在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])
您正在向文件写入最后一次输入,不是列表中的元素