写入文件对象时返回值

在 Python 2 中,直接写入文件句柄返回 None

Python 2.x >= 2.3

hi = sys.stdout.write('hello world\n')
# Out: hello world
type(hi)
# Out: <type 'NoneType'>

在 Python 3 中,写入句柄将返回写入文本时写入的字符数,以及写入字节时写入的字节数:

Python 3.x >= 3.0

import sys

char_count = sys.stdout.write('hello world 🐍\n')
# Out: hello world 🐍
char_count
# Out: 14

byte_count = sys.stdout.buffer.write(b'hello world \xf0\x9f\x90\x8d\n')
# Out: hello world 🐍
byte_count
# Out: 17