Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Print to file

  • open
  • print

We can also use the print function to print (or write) to a file. In this case the same rules apply as printing to standard output (automatically adding a trailing newline, inserting a space between parameters). We do this by passing the file-handle as the value of the file parameter of print.


filename = 'out.txt'
with open(filename, 'w') as fh:
    print("Hello", "World", file=fh)