首页 > 解决方案 > 尝试在 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 文件,但在文件内部,它一直写“无”而不是学生信息。我怎样才能解决这个问题?

这可能是一个愚蠢的问题,但我是编码新手。

标签: pythonpython-3.x

解决方案


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()函数的重新运行。


推荐阅读