本文簡要介紹 python 語言中 numpy.fromfile
的用法。
用法:
numpy.fromfile(file, dtype=float, count=- 1, sep='', offset=0, *, like=None)
從文本或二進製文件中的數據構造一個數組。
一種讀取具有已知數據類型的二進製數據以及解析簡單格式化的文本文件的高效方法。使用 tofile 方法寫入的數據可以使用此函數讀取。
- file: 文件或 str 或路徑
打開文件對象或文件名。
- dtype: 數據類型
返回數組的數據類型。對於二進製文件,它用於確定文件中項目的大小和字節順序。支持大多數內置數字類型,並且可能支持擴展類型。
- count: int
要閱讀的項目數。
-1
表示所有項目(即完整文件)。- sep: str
如果文件是文本文件,則項目之間的分隔符。空(“”)分隔符表示文件應被視為二進製文件。分隔符中的空格 (" ") 匹配零個或多個空白字符。僅由空格組成的分隔符必須至少匹配一個空格。
- offset: int
與文件當前位置的偏移量(以字節為單位)。默認為 0。僅允許用於二進製文件。
- like: array_like
允許創建非 NumPy 數組的引用對象。如果作為
like
傳入的類似數組支持__array_function__
協議,則結果將由它定義。在這種情況下,它確保創建一個與通過此參數傳入的數組對象兼容的數組對象。
參數:
注意:
不要依賴組合文件和
fromfile
用於數據存儲,因為生成的二進製文件不是平台獨立的。特別是,不保存字節順序或數據類型信息。數據可獨立於平台存儲.npy
格式使用numpy.save和numpy.load反而。例子:
構造一個ndarray:
>>> dt = np.dtype([('time', [('min', np.int64), ('sec', np.int64)]), ... ('temp', float)]) >>> x = np.zeros((1,), dtype=dt) >>> x['time']['min'] = 10; x['temp'] = 98.25 >>> x array([((10, 0), 98.25)], dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
將原始數據保存到磁盤:
>>> import tempfile >>> fname = tempfile.mkstemp()[1] >>> x.tofile(fname)
從磁盤讀取原始數據:
>>> np.fromfile(fname, dtype=dt) array([((10, 0), 98.25)], dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
存儲和加載數據的推薦方式:
>>> np.save(fname, x) >>> np.load(fname + '.npy') array([((10, 0), 98.25)], dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
相關用法
- Python numpy fromfunction用法及代碼示例
- Python numpy frombuffer用法及代碼示例
- Python numpy fromregex用法及代碼示例
- Python numpy fromstring用法及代碼示例
- Python numpy fromiter用法及代碼示例
- Python numpy frompyfunc用法及代碼示例
- Python numpy frexp用法及代碼示例
- Python numpy floor用法及代碼示例
- Python numpy float_power用法及代碼示例
- Python numpy flatiter用法及代碼示例
- Python numpy fft.rfft用法及代碼示例
- Python numpy fft.irfft用法及代碼示例
- Python numpy fmod用法及代碼示例
- Python numpy find_common_type用法及代碼示例
- Python numpy flatnonzero用法及代碼示例
- Python numpy format_float_scientific用法及代碼示例
- Python numpy fabs用法及代碼示例
- Python numpy fft.rfft2用法及代碼示例
- Python numpy fft.ihfft用法及代碼示例
- Python numpy fft.fftfreq用法及代碼示例
- Python numpy flip用法及代碼示例
- Python numpy full用法及代碼示例
- Python numpy fft.irfftn用法及代碼示例
- Python numpy fft.irfft2用法及代碼示例
- Python numpy fix用法及代碼示例
注:本文由純淨天空篩選整理自numpy.org大神的英文原創作品 numpy.fromfile。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。