Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python f、 写下,如何修复页面顶部的标题?_Python_Python 3.x_File - Fatal编程技术网

Python f、 写下,如何修复页面顶部的标题?

Python f、 写下,如何修复页面顶部的标题?,python,python-3.x,file,Python,Python 3.x,File,我有一个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'))

我有一个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

因为您是在附加模式下打开文件的,所以只有在文件是新创建的情况下才应该写入头。为此,您可以使用file对象的
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')

完成!非常感谢。