Python | file parameter in print ()

It serves two main purposes:

 Print to STDERR Print to external file 

Note: the parameter & # 39; file & # 39; only found in Python 3.x or later.

Printing to STDERR:

Specify the file parameter as sys.stderr instead of the default. This is very useful when debugging a small program (otherwise it would be better to use a debugger).

# Code for printing in STDERR

import sys


print ( `GeeksForGeeks` , file = sys.stderr)



Print to a specific file:

Replace the default with a file parameter with the name of the desired file. If the file does not exist, a new file with that name is created and written to.

# Code to print to file

sample = open ( `samplefile.txt` , ` w` )


print ( `GeeksForGeeks` , file = sample)

sample.close ( )

Output (in “samplefile .txt “) :


Notes Note: try this in the interpreter on your system, as such a file is not available in the Online IDE.