简体   繁体   中英

python3-numpy: Write header only if file is new with numpy savetxt

I am appending lines to an output file several times using numpy.savetxt similar to the mwe below. However, I would like to only write the header to the file once, ie, if it didn't exist before. Other than checking every time I'm appending to the file if it already exists or not, is there a simpler way to achieve this?

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np

def write(array):
    with open('test.dat', 'ab') as f:
        np.savetxt(f, array, header='test header')

write([1, 2, 3])
write([4, 5, 6])

Output (test.dat):

# test header
1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00
# test header
4.000000000000000000e+00
5.000000000000000000e+00
6.000000000000000000e+00

Instead of this output, I would like only one header line at the top of the file.

I would do something like so:

import numpy as np
import os

def write(array):
    header = '' # set empty header
    if not os.path.isfile('test.dat'): # checks if the file exists
        header = 'Test header' # if it doesn't then add the header
    with open('test.dat', 'ab') as f:
        np.savetxt(f, array, header=header)

write([1, 2, 3])
write([4, 5, 6])

If you do not want to check if the file exists each time you write to the file, you could adopt a workaround:
Whenever you write to the file, **do not* write the header at all. Only when you're done with all your write operations, insert the header at the beginning of the file.

Here is a SO answer explaining how to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM