Python print to file With Examples

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:

  • You don’t want to convert your project to use logger temporarily
  • Keep the print statements handy and portable

Let’s get started.

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.

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.

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

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:
print-to-file-global
Let’s try another way of doing this.

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:

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. 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.

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

By admin

Leave a Reply

%d bloggers like this: