我有以下代码:
with open(True, 'w') as f:
f.write('Hello')
为什么此代码打印文本 Hello
而不是引发错误?
最佳答案
来自built-in function documentation on open()
:
open(file, mode='r', buffering=-1...
file is either a string or bytes object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped
os
module documentation 中进一步描述了“整数文件描述符” :
For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2. Further files opened by a process will then be assigned 3, 4, 5, and so forth.
因为 bool 值是 int
的子类,False
可以与 0
和 True
与 互换使用>1
。因此,打开一个True
的文件描述符与打开一个1
的文件描述符是一样的,都会选择标准输出。
关于python - 为什么 open(True, 'w' ) 会像 sys.stdout.write 一样打印文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32841090/