如何将 header 写入文本文件?

How to write header to a text file?

我将我的代码输出写入 .txt 文件。我需要在 .txt 文件中放置一个 header。像这样:

id, width, height, weight
1     252    455      555
2     544    525      475
3     4752   2445     58.5 
4     452.3  125.2    1422.36

我写了这段代码,但它只是在我每次写数字时写 header。我只需要写一次header。其余的应该是数字。我想知道该怎么做?

header = "id, width, height, weight"
with open(outputFilename, 'a') as file_writer:
    file_writer.write(header + "\n")
    file_writer.close
    
    
output_string=f"{f1}, {f2},  {f3}, {f4}\n"
print(output_string)
with open(outputFilename, 'a') as file_writer:
    file_writer.write(output_string)

您可以检查输出文件是否为空,如果输出文件为空,则写入文件头。你可以看到例子 here.

filesize = os.path.getsize(outputFilename)

if filesize == 0:
    header = "id, width, height, weight"
    with open(outputFilename, 'a') as file_writer:
            file_writer.write(header + "\n")
            file_writer.close