Knowledge for the World

Printing in Python

  • by Tyler (210)
  • 10 minutes

In this guide we're going to cover how to print in Python, both to a file and to standard output. Printing is useful for many things, but when you're learning Python it's especially useful for debugging and logging.


There are two steps to writing text to a file: open and write.

To open a file for writing, we should always use the with keyword. Using with is advantageous because it handles properly closing the file even if an exception is raised.

with open('filename.txt', 'w') as fh:
    fh.write('This is line 1')

In the above code, fh is the file handle created by the open function. fh.write writes a single line to the open file. Notice the second argument to the open function, w, ensures that the file is opened for writing.

To test this out, you can create a file called and paste the above code. Then run it like this (from the Terminal):


In your current directory, you should see a file called filename.txt. Check the contents:

cat filename.txt

Feel free to edit the file and add extra fh.write lines to see what happens. After you run the file, you'll notice that the contents have been overwritten. That is the nature of the w flag. It opens the for writing and truncates the file.


If you're running a Python program and want to print text to the console, you can simply use the print function.

print('Here I am!')

On Unix systems (macOS, Linux, BSD, etc), everything is a file. When you use the print function you're actually writing to a file called standard output, which is abbreviated stdout. And the terminal reads from this file and displays it on the screen.

To prove this, try executing the following code snippets. They are effectively the same thing:

with open('/dev/fd/0', 'w') as fh:
    fh.write('Writing to stdout!)

/dev/fd/0 is the stdout file.

import sys

sys.stdout.write('Writing to stdout!')
print('Writing to stdout!')

When you print, you'll often want to format the text. There are many formatting options, but we're going to cover the most commonly used.

Often you'll want to use variables inside a string of text. To do this, you'll use formatted string literals or f-strings.

>>> name = 'Ben Franklin'
>>> f'My name is not {name}.'
'My name is not Ben Franklin.'

You can also do number formatting like this:

>>> score = 0.9
>>> f'{score:.1%}'

More details can be found in the formatting specification.

Importantly, the f-string can also be used as an argument to the print function:

>>> score = 0.9
>>> print(f'You scored {score:.1%} on your test.')
Series: Python Basics
Show all in this series