Python | file parameter in print()
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.
Recommended Posts:
- Python | sep parameter in print()
- Python | end parameter in print()
- Python | Key-Value to URL Parameter Conversion
- Python | Split and Pass list as separate parameter
- reStructuredText | .rst file to HTML file using Python for Documentations
- Reading Python File-Like Objects from C | Python
- File Searching using Python
- Python | Kivy .kv File
- File Objects in Python
- File Handling in Python
- Python | ScreenManager in Kivy using .kv file
- How to get the permission mask of a file in Python
- Python | Accordion in kivy using .kv file
- Python | TextInput in kivy using .kv file
- Python | File chooser in kivy
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



