TypeError: write() argument must be str, not bytes (Python 3 vs Python 2 )

前端 未结 1 998
南旧
南旧 2021-02-19 02:01

The below code works perfectly for python 2.7.13

import os
with open(\'random.bin\',\'w\') as f:
    f.write(os.urandom(10))

But throws error f

相关标签:
1条回答
  • 2021-02-19 02:33

    In Python 3 it makes a difference whether you open the file in binary or text mode. Just add the b flag to make it binary:

    with open('random.bin','wb') as f:
    

    This works in Python 2 too.

    0 讨论(0)
提交回复
热议问题