Files
python3-cookbook/source/c05/p02_printing_to_file.rst

26 lines
624 B
ReStructuredText
Raw Permalink Normal View History

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