【问题标题】:f.write, how can i fix the header at the top of the page?f.write,如何修复页面顶部的标题?
【发布时间】:2020-02-27 18:03:54
【问题描述】:

我有一个 python 代码,它给了我几个输出值,我创建了一个文件,每次运行都可以在同一个 txt 文件中添加一行新数据。问题是每次运行都会写入标题,我只想修复文件顶部的标题。

这是我所拥有的:

with open('Trial.txt', 'a') as fd:
    fd.write('{a:^8}  {b:^8}    {c:^8}      {d:^8}  {e:^8}'.format(a='DIA', b='Dia', c='Len',d='PRO',e='time'))
    fd.write("\r")
    fd.write(f'    {magnitude}          {diameter}        {Length}      {Pro_code}     {Time}')
    fd.write("\r\n") 

输出是这样的:

    DIA            Dia           Len           PRO           time
    8.0            7000          500      0.0052297            141
    DIA            Dia           Len           PRO           time
    7.0            6000          400      0.003237            161

这是我想要得到的:

    DIA            Dia           Len           PRO           time
    8.0            7000          500      0.0052297           141
    7.0            6000          400      0.003237            161

【问题讨论】:

    标签: python python-3.x file


    【解决方案1】:

    由于您以追加模式打开文件,因此只有在新创建文件时才应写入标题。为此,您可以使用文件对象的 tell 方法并检查它是否在位置 0 以判断它是否是新文件,如果是,则仅写入标题:

    with open('Trial.txt', 'a') as fd:
        if fd.tell() == 0:
            fd.write('{a:^8}  {b:^8}    {c:^8}      {d:^8}  {e:^8}\r\n'.format(a='DIA', b='Dia', c='Len',d='PRO',e='time'))
        fd.write(f'    {magnitude}          {diameter}        {Length}      {Pro_code}     {Time}\r\n')
    

    【讨论】:

    • 完成!谢谢!
    猜你喜欢
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多