This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: error writing to file in binary mode - python 3.6.3
Type: Stage: resolved
Components: IO Versions: Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: lopgok, serhiy.storchaka
Priority: normal Keywords:

Created on 2018-01-08 15:55 by lopgok, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg309669 - (view) Author: jeff deifik (lopgok) Date: 2018-01-08 15:55
I am running python 3.6.3 on cygwin / windows.

Here is a test program to demonstrate the bug:

#!/usr/bin/env python3

fp = open("bug_out.txt", "ab")
buff = 'Hello world'
print('type of buff is', type(buff))
bin_buff = bytes(buff,  'utf-8')
print('type of bin_buff is', type(bin_buff))
print(bin_buff, file=fp)

Here is the output:
./bug.py
type of buff is <class 'str'>
type of bin_buff is <class 'bytes'>
Traceback (most recent call last):
  File "./bug.py", line 8, in <module>
    print(bin_buff, file=fp)
TypeError: a bytes-like object is required, not 'str'

The python type system things bin_buff has type bytes, but when I try to print it, the print function thinks it is of type str.
msg309672 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2018-01-08 16:07
print() converts all its arguments to string by calling str(). The resulting strings are written to the output file.

print(bin_buff, file=fp) is equivalent to

    fp.write(str(bin_buff))
    fp.write('\n')

If you will run Python with options -b or -bb you will get a warning or an error from str(bin_buff) because this operation can be ambiguous. It is better to use an explicit repr() for converting bytes to str if you want to get the representation of the bytes object as a Python literal, or convert it to a string with specifying explicit encoding: str(bin_buff, 'utf-8') or bin_buf.decode('utf-8').
History
Date User Action Args
2022-04-11 14:58:56adminsetgithub: 76701
2018-01-08 16:07:38serhiy.storchakasetstatus: open -> closed

nosy: + serhiy.storchaka
messages: + msg309672

resolution: not a bug
stage: resolved
2018-01-08 15:55:31lopgokcreate