Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.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中,当写入文件时,如何确保数据保存在一行上?_Python_File_Line - Fatal编程技术网

在Python中,当写入文件时,如何确保数据保存在一行上?

在Python中,当写入文件时,如何确保数据保存在一行上?,python,file,line,Python,File,Line,我有以下代码: with open("students2.txt", mode="w", encoding="utf-8") as my_file: for each_item in names: student_grade=input("Enter the grade for " +str(each_item)) my_file.write(each_item+", "+student_grade) 当数据保存到文件时,我需要按如下方式保存: 每个

我有以下代码:

with open("students2.txt", mode="w", encoding="utf-8") as my_file:
    for each_item in names:
         student_grade=input("Enter the grade for " +str(each_item))
         my_file.write(each_item+", "+student_grade)
当数据保存到文件时,我需要按如下方式保存: 每个项目,学生的成绩,这可能是78岁的迈克。 然后下一个将保存在新行上

我错过了什么

 my_file.write(each_item+", "+student_grade+"\n");
用这个换一行就行了


只需使用此选项将其添加到新的行中。

谢谢您的回复。然而,它仍然保存不正确。逗号和学生成绩将插入新行。请尝试将每个_项转换为字符串。谢谢您的回复。然而,它仍然保存不正确。逗号和学生成绩将插入新行。请尝试将每个_项转换为字符串。