簡體   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