python - 为什么以下 python 代码不打印到文件

标签 python

from sys import stdout
stdout = open('file', 'w')
print 'test'
stdout.close()

确实创建了文件,但它不包含任何内容。

我不得不使用

import sys
sys.stdout = open('file', 'w')
print 'test'
sys.stdout.close()

但是 from ... import... 不会自动使名称可用吗?为什么我仍然必须使用 sys.stdout 而不是 stdout

最佳答案

问题是这样的:print 等同于 sys.stdout.write()

因此,当您执行 from sys import stdout 时,变量 stdout 将不会被 print 使用。

但是当你这样做的时候

import sys
print 'test'

它实际上写入了指向您打开的文件sys.stdout

分析

from sys import stdout
stdout = open('file', 'w')
print 'test' # calls sys.stdout.write('test'), which print to the terminal
stdout.close()

import sys
sys.stdout = open('file', 'w')
print 'test' # calls sys.stdout.write('test'), which print to the file
sys.stdout.close()

结论

这有效...

from sys import stdout
stdout = open('file', 'w')
stdout.write('test')
stdout.close()

关于python - 为什么以下 python 代码不打印到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14544893/

相关文章:

c# - 线性代数库

python - 机器学习算法中的示例顺序 (Scikit Learn)

python - matplotlib 散点图 : TypeError: unhashable type: 'numpy.ndarray'

python - 如何使用 python 从 GUI 传递 SQL 查询并获取结果并在表中显示结果

python - 如何在python中将标称数据转换为数值?

python - 从 numpy 矩阵中最优提取列

javascript - 在 Python 中使用 Splice 移动函数

python - 将用户 ID 的类型更改为 UUID

python - 重复for循环的迭代

python - 将 UTF-8(或其他 8 位编码)压缩为 7 位或更少位