Files
python3-cookbook/source/c05/p02_printing_to_file.rst
2015-12-28 19:34:04 +08:00

26 lines
624 B
ReStructuredText

============================
5.2 打印输出至文件中
============================
----------
问题
----------
你想将 ``print()`` 函数的输出重定向到一个文件中去。
----------
解决方案
----------
``print()`` 函数中指定 ``file`` 关键字参数,像下面这样:
.. code-block:: python
with open('d:/work/test.txt', 'wt') as f:
print('Hello World!', file=f)
----------
讨论
----------
关于输出重定向到文件中就这些了。但是有一点要注意的就是文件必须是以文本模式打开。
如果文件是二进制模式的话,打印就会出错。