如何输出到txt(Programming in Python with Processing 3)

How to output to txt (Programming in Python with Processing 3)

我目前正在做一个项目,该项目的一部分是将一些东西输出到项目目录中的一个单独的 .txt 文件中,我已经完成了,但是我有一个问题,一切都很好,但是 我不想每次都创建一个新文件,但我想将所有内容和所有记录都存储在一个文件中,并且它们不断累加,有人可以帮助我吗?

这是我想出的部分代码,不要为“%d”等烦恼。我只需要输出方面的帮助:

output = createWriter("rekordi.txt")
            output.print("Tvoj zadnji rekord je " + str(millis()/1000-sekunde) + " sekund || ob " + str(datum.strftime("%I:" + "%M" + " %p" + " na " + "%d." + "%b"))) # Write the date to the file
            output.flush()# Writes the remaining data to the file
            output.close()# Finishes the file
with open("rekordi.txt", "a", buffering=0) as f:
      f.write("write some data") 

文件模式"a"会将所有数据附加到文件
buffering=0表示数据将直接写入文件(就像使用flush())

您要做的是以append 模式打开文件。如果它不存在,这将创建它,如果它已经存在,它将附加到它而不是覆盖它。像这样的东西应该做你想做的事:

my_file_path = 'output_record.txt'
with open(my_file_path, 'a') as outfile:
    outfile.write(<output data here in string format> + '\n') # \n for newline

with ... 是上下文管理器块,这意味着当该代码块退出时文件将自动关闭。 'a' open 的第二个参数指定 append 模式。

希望对您有所帮助,编码愉快(周五快乐)!