LoginSignup
0
1

More than 5 years have passed since last update.

numpy > np.savetxt()する時の open(OUT_FILE ,'w+') > TypeError: Mismatch between array dtype ('<U11') and format specifier ('%s') > open(OUT_FILE, 'wb+')にする

Last updated at Posted at 2017-08-04
動作環境
GeForce GTX 1070 (8GB)
ASRock Z170M Pro4S [Intel Z170chipset]
Ubuntu 16.04 LTS desktop amd64
TensorFlow v1.1.0
cuDNN v5.1 for Linux
CUDA v8.0
Python 3.5.2
IPython 6.0.0 -- An enhanced Interactive Python.
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)

5行の文字列をファイル出力するコード。

test_170805a.py
import numpy as np

OUT_FILE = 'out_170805.txt'
TEXT = 'hello world'

with open(OUT_FILE, 'wb+') as fhndl:
    hdr = np.array(TEXT).reshape(1,)
    for loop in range(5):
        np.savetxt(fhndl, hdr, delimiter=' ', fmt='%s')

このようなコードを実装したのだが、気になったのがopen()を'b'付きでしていること。

テキストなので'b'ではないのでないかと思った。
'b'なしのopen()にすると以下のエラーになった。

...
Traceback (most recent call last):
  File "test_170805a.py", line 9, in <module>
    np.savetxt(fhndl, hdr, delimiter=' ', fmt='%s')
  File "/home/yasokada/.local/lib/python3.5/site-packages/numpy/lib/npyio.py", line 1219, in savetxt
    % (str(X.dtype), format))
TypeError: Mismatch between array dtype ('<U11') and format specifier ('%s')

以下を見つけた。
https://stackoverflow.com/questions/35372829/numpy-savetxt-resulting-a-formatting-mismatch-error-in-python-3-5

savetxt opens the file in wb mode, and thus writes everything as bytes.

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1