繁体   English   中英

python3-numpy:仅当文件是新的 numpy savetxt 时才写入 header

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

我使用类似于下面的 mwe 的 numpy.savetxt 多次向 output 文件附加行。 但是,我只想将 header 写入文件一次,即,如果它以前不存在。 除了每次我附加到文件时检查它是否已经存在,有没有更简单的方法来实现这一点?

#!/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

而不是这个 output,我只想在文件顶部有一个 header 行。

我会这样做:

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])

如果您不想在每次写入文件时检查文件是否存在,您可以采用一种解决方法:
每当您写入文件时,**不要*写入 header。 只有在完成所有写入操作后,才在文件开头插入 header。

是一个解释如何做的答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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