python打印到文件_Python打印到文件

python打印到文件

1. Python打印到文件 (1. Python Print to File)

In this lesson, we will see how we can route our python print statements in to a file. This means that whatever we try to print will be saved to a file. This can come handy when:

在本课程中,我们将看到如何将python打印语句路由到文件中。 这意味着我们尝试打印的任何内容都会保存到文件中。 在以下情况下可以派上用场:

  • You don’t want to convert your project to use logger temporarily

    您不想将项目转换为临时使用记录器

  • Keep the print statements handy and portable

    保持打印报表方便携带

Let’s get started.

让我们开始吧。

2.打印到文件 (2. Printing to file)

When we need to print our output to files, this can be achieved in two ways which are both simple to use. Let’s look at them one by one.

《python打印到文件_Python打印到文件》

当我们需要将输出打印到文件时,可以通过两种都易于使用的方式来实现。 让我们一一看一下。

2.1)将路线设置为全局 (2.1) Setting the route as global)

To start, we can set the output route Python needs to consider as a global variable for our program. This means that you need to make a simple assignment and then call print just like we do any other time.

首先,我们可以设置Python需要考虑的输出路径作为程序的全局变量。 这意味着您需要进行简单的分配,然后像其他时间一样调用print。

Let’s put above logic in a simple code snippet:

让我们将上面的逻辑放在一个简单的代码片段中:

import sys

sys.stdout = open('output.txt','wt')
print("Hello Python!")
print("We are printing to file.")

When we run the above program, we see that a new file is created in the same directory with name ‘output.txt’ with following contents:

《python打印到文件_Python打印到文件》

Let’s try another way of doing this.

当我们运行上述程序时,我们看到在同一个目录中创建了一个名为’output.txt’的新文件,其内容如下:

让我们尝试另一种方式。

2.2)确定每个打印呼叫 (2.2) Deciding with each print call)

There can be times when you do not want to set the print to file for the entire program but just for a few calls in the program. This can be achieved as well. Let’s try to achieve this in a simple code snippet:

有时您可能不想为整个程序将打印设置为文件,而只为程序中的几次调用设置文件。 这也可以实现。 让我们尝试通过一个简单的代码片段实现这一目标:

print("Hello Python!", file=open('output.txt','a'))
print("We are printing to file.", file=open('output.txt','a'))

When we run this program, the same output is achieved. The advantage of this method is that we can decide, with each print call if we want to print the output to a file or not.

当我们运行该程序时,将获得相同的输出。 这种方法的优点是,我们可以在每次打印调用时决定是否要将输出打印到文件中。

3.结论 (3. Conclusion)

In this quick post, we saw how we can print our statements to a file using Python 3. Although printing to file is cool but we should instead consider logging in Python when we need this kind of behavior with a lot of other customizations.

在这篇快速文章中,我们看到了如何使用Python 3将语句打印到文件中。尽管打印到文件很酷,但是当我们需要这种行为以及许多其他自定义设置时,我们应该考虑使用Python登录

That’s all for routing python print() to file.

这就是将python print()路由到文件的全部内容。

翻译自: https://www.journaldev.com/18424/python-print-to-file

python打印到文件

    原文作者:cunchi4221
    原文地址: https://blog.csdn.net/cunchi4221/article/details/107474440
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞