python - 为什么 open(True, 'w' ) 会像 sys.stdout.write 一样打印文本?

标签 python python-3.x

我有以下代码:

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 可以与 0True 互换使用>1。因此,打开一个True的文件描述符与打开一个1的文件描述符是一样的,都会选择标准输出。

关于python - 为什么 open(True, 'w' ) 会像 sys.stdout.write 一样打印文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32841090/

相关文章:

python - 字符串格式 : % vs. .format 与 f-string 文字

python - 无法从 AWS 机器上的 python 中的 selenium 调用 firefox

python - Python 列表中 x += x 和 x = x + x 的区别

python - 类型错误 : can only concatenate tuple (not "str") to tuple in python

python - 从字符串中删除变音符号以实现搜索功能

python-3.x - Tkinter 复制到剪贴板在 PyCharm 中不起作用

python-3.x - 使用 scipy.optimize.curve_fit 时如何将参数传递给拟合函数

python - 如何在Windows上从C中的CreateProcess执行Python脚本?

python - 在ubuntu中使用livestreamer录制

python - 将项目插入列表中的列表