python - 尝试在 Python 中的文件上写入格式化文本时出现问题
问题描述
我编写了这个 python 脚本来查找学生的及格成绩、不及格成绩和平均成绩,并将它们写在 .txt 文件中,但我遇到了脚本无法按预期工作的问题。
这是负责创建文件和写入数据的代码部分:
avg_f = print('Student: {:10s} Passing grades: {:<10d} Failing grades: {:<10d} Average: {:3.2f}'.format(student_name + " " + student_surname, p_g, f_g, avg))
u_ch = input("Do you want to save? Y/N: ")
while str.isalpha(u_ch) == False:
u_ch = input("You can't insert numbers or special characters.\nDo you want to save? Y/N: ")
while u_ch.lower() != "y" and u_ch.lower() != "n":
u_ch = input("Invalid input. Y/N: ")
if u_ch.lower() == "n":
print("Arresting the script...")
exit()
else:
print()
barr()
file = open("Students.txt", "a")
file.writelines(str(avg_f))
print("The file was successfully saved.")
file.close()
当我运行脚本时,它会生成一个 .txt 文件,但在文件内部,它一直写“无”而不是学生信息。我怎样才能解决这个问题?
这可能是一个愚蠢的问题,但我是编码新手。
解决方案
print()函数在控制台上打印并返回None
. 您将此返回值分配给一个变量,然后将其放入文件中。
作品。
将其更改为
avg_f = 'Student: {:10s} Passing grades: {:<10d} Failing grades: {:<10d} Average: {:3.2f}'.format(student_name + " " + student_surname, p_g, f_g, avg)
print(avg_f)
所以你的变量保存字符串而不是print()
函数的重新运行。
推荐阅读
- azure-maps - 是否有用于地理定位的打字稿或 javascript api - 在 Azure Maps npm 模块 azure-maps-rest 中获取 IP 到位置预览功能
- python - 无法选择正确的 Cookie 以使用 python 代码登录
- python - pythonscript没有用pdflatex编译
- angular - 如何根据屏幕上剩余的可用空间向数组添加更多项目
- python - 在子类 QtCore.QAbstractItemModel 上使用 QSortFilterProxyModel 时,PyQt5 Treeview 不需要扩展索引
- java - java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageButton 不能转换为 android.widget.Button
- react-native - React Native“显示检查器”重新加载应用程序
- java - Java中的对象在内存中的字段和值遍历
- javascript - 传递 ID 以在 vue 中为特定项目打开模式的问题
- mysql - MySQL 从带有两个关系表的选择查询中提取 JSON