简体   繁体   English

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

[英]In Python when writing to a file how can you make sure the data is saved on one line?

I have the following code:我有以下代码:

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)

When the data saves to the file I need it to save like this: each_item,student_grade so this might be Mike,78.当数据保存到文件时,我需要像这样保存:each_item,student_grade 所以这可能是 Mike,78。 Then the next one is saved on a new line然后下一个保存在新行上

What have I missed?我错过了什么?

 my_file.write(each_item+", "+student_grade+"\n");

Just use this to put it on a new line.只需使用它来将其放在新行上。

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

相关问题 如何在Python中写入文件之前确保文件存在或可以创建? - How to make sure a file exists or can be created before writing to it in Python? 在Python中写入文件时如何写入新行? - How do you write to a new line when writing to a file in Python? 在用 Python 将字典写入 YAML 文件时,如何确保 YAML 文件中的字符串根据 '\n' 进行拆分? - When writing in Python a dictionary to a YAML file, how to make sure the string in the YAML file is split based on '\n'? 不确定如何使一行代码在python中工作 - not sure how to make one line of code work in python 为什么将保存的文本文件加载到 tkinter (python) 的列表框中时,将每个保存的数据输入显示为一行? - Why when loading the saved text file into list-box of tkinter (python) displays every saved data input into one line? 如何确保 Python 进入文件行的末尾? - How to make sure Python goes into the end of a file line? 如何确保python找到必要的数据文件? - How can I make sure that python finds the necessary data files? 如何确保在FocusOut上保存tkinter条目的内容? - How can I make sure the content of a tkinter entry is saved on FocusOut? Python中写入文件时无法添加新行 - I can't add a new line when writing a file in Python 使用python写入CSV文件时如何锁定CSV文件 - How do you lock a CSV file when writing to it using python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM