如何在Python中将带有永久标头的数据写入文件?

问题描述

我想使用Python将一些简单的数据写入文件。应该有1个永久性标头,Date last Run,并且在该标头下有date_file,它被不变地追加。 (date_file一个每次都会更改的字符串。

这是我的代码

log_location = r'c:\data\OOP\Desktop\new_location'
with open(log_location + '\\' + 'logfile.txt','w') as output:
    output.write('Date last Run')
    output.write(date_file)

这是我的输出

Date last Run20200907

我希望我的输出是:

Date last Run
20200907

当我在9月8日运行它时,我希望它看起来像这样:

Date last Run
20200907
20200908

等因此,date_file会附加到前一行的最后一行,而Date last Run应该是永久的

解决方法

您始终可以查看文件的大小,如果文件头为空,则可以写头文件:

log_location = r'c:\data\OOP\Desktop\new_location'
with open(log_location + '\\' + 'logfile.txt','a') as output:
    if output.tell() == 0:
        output.write('Date last Run\n')
    output.write(date_file + '\n')