在open =下使用print

时间:2019-01-29 14:25:12

标签: python python-3.x file-io

我正在尝试将以下代码打印到文件中。 查看堆栈溢出时,我发现了file = open代码,但它似乎没有写入文件。

PS。我还没有创建文件

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'))

4 个答案:

答案 0 :(得分:1)

在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时都要求硬盘驱动器工作。 flush输出缓冲区告诉python立即写入数据,例如f.flush()

print语句实际上确实有一个flush参数,因此可能与该参数高度相关。不过,我还是建议使用with语句。

答案 1 :(得分:0)

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))

请注意,打开的'a'选项用于附加。您还可以使用“ w”进行写入。

答案 2 :(得分:0)

我明白了。我打开文件,然后在打印结束时使用file =。

newFile = open("results.txt", 'w')

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=newFile)

newFile.close()

答案 3 :(得分:0)

尝试一下:

lxml