LoginSignup
7
6

More than 5 years have passed since last update.

python3 の tempfile + write はデフォルトのままだと <object>.write(<a bytes-like object>) が求められる

Last updated at Posted at 2018-02-22

Python3 で普通に wf.write とか使ってると間違えやすいbytesの話です

mode='w+b' がデフォルトで採用されているからであって、modeを指定してやればよかっただけの話でした。コメントで指摘してくださった @tag1216 さんに感謝。

    import tempfile

    with tempfile.NamedTemporaryFile(delete=False) as tf:
        word = "hoge" + '¥n'
        tf.write(word)

    >>> TypeError: a bytes-like object is required, not 'str'

型違えば怒られますよね……ということでstr型をbytes型に変えておきましょう。 でも良いのですが mode='w+t'を指定してテキストモードで開いた方がスマートに解決できます

# bytes型に変換してから書き込む
import tempfile

with tempfile.NamedTemporaryFile(delete=False) as tf:
    word = "hoge" + '¥n'
    word_bytes = word.encode('uft-8')
    tf.write(word_bytes)
# mode='w+t'を指定して開く
import tempfile

with tempfile.NamedTemporaryFile(mode='w+t', encoding='utf-8', delete=False) as tf:
    tf.write('hoge' + '¥n')

今度tempfileの使い方でまとめておくので雑記事で許してください。では

7
6
1

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
7
6