Sunday, November 23, 2025
HomeLanguagesfile parameter of Python’s print() Function

file parameter of Python’s print() Function

print() function in Python3 supports a ‘file‘ argument, which specifies where the function should write a given object(s) to. If not specified explicitly, it is sys.stdout by default.

It serves two essential purposes:

Print to STDERR
Print to external file

Note : The ‘file’ parameter is found only in Python 3.x or later.
 
Printing to STDERR :

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




# Code for printing to STDERR
import sys
  
print('GeeksForGeeks', file = sys.stderr)


Output :

GeeksForGeeks

 
Printing to a specific file :

Instead of the default value, specify the file parameter with the name of the required file. If the file does not exist, a new file by that name is created and written to.




# Code for printing to a file
sample = open('samplefile.txt', 'w')
  
print('GeeksForGeeks', file = sample)
sample.close()


Output (in “samplefile.txt”) :

GeeksForGeeks

Note : Try this in interpreter on your system, since such file can’t be accessed on Online IDE.

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32409 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6908 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6865 POSTS0 COMMENTS
Umr Jansen
6852 POSTS0 COMMENTS