提问者:小点点

使用带open的print=


我正试图将下面的代码打印到一个文件中。通过查看堆栈溢出,我发现file=open代码,但它似乎没有写入文件。

另外,我还没有创建文件

print("Average Grade " + str(average), "At least 70% " + 
      str(Grade1), "60% - 69% " + str(Grade2), "50% - 59% " +
      str(Grade3), "40% - 49% " + str(Grade4), "Less than 40% " + 
      str(Grade5), "Highest Grade " +
      str(max_grade), "Student Name:" + str(student_name), sep="\n", 
      file=open("results.txt", 'a'))

共3个答案

匿名用户

在python中,我们通常不使用print语句。考虑以下替代方案。使用“上下文管理器”允许您编写多行,如果程序在写入文件时抛出错误,也有助于避免某些问题。

with open('results.txt', 'a') as f:
    line = "Average Grade " + str(average), "At least 70% " + str(Grade1), "60% - 69% " + str(Grade2), "50% - 59% " + str(Grade3), "40% - 49% " + str(Grade4), "Less than 40% " + str(Grade5), "Highest Grade " + str(max_grade), "Student Name:" + str(student_name)
    f.write(line)

顺便说一句,如果您以交互方式执行此操作,您可能不会立即看到写入文件的数据-这在使用终端而不是运行脚本时可能是一个真正的混淆点!发生的情况是python将数据以大数据块的形式写入文件,而不是每次调用f.write时都要求硬盘执行工作flushing输出缓冲区告诉python立即写入数据-例如f.flush()

print语句实际上有一个flush参数,这可能与此高度相关。尽管如此,我还是建议使用with语句。

匿名用户

试试这个:

file = open("Here you put your path to a file, but replace '\' with '\\'", 'w+')
# That opened your file in 'write' mode, and '+' means that if it does not 
# exist, one will be created
file.write("Average Grade " + str(average), "At least 70% " + 
str(Grade1), "60% - 69% " + str(Grade2), "50% - 59% " +
str(Grade3), "40% - 49% " + str(Grade4), "Less than 40% " + 
str(Grade5), "Highest Grade " +
str(max_grade), "Student Name:" + str(student_name))
file.close()

匿名用户

with open("results.txt", 'a') as f:
    f.write("Average Grade " + str(average), "At least 70% " + 
    str(Grade1), "60% - 69% " + str(Grade2), "50% - 59% " +
    str(Grade3), "40% - 49% " + str(Grade4), "Less than 40% " + 
    str(Grade5), "Highest Grade " +
    str(max_grade), "Student Name:" + str(student_name))

请注意,open中的“a”选项用于追加。您也可以使用“w”进行写入。