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()
- reStructuredText | .rst file to HTML file using Python for Documentations
- File Handling in Python
- File Objects in Python
- File Searching using Python
- Junk File Organizer in Python
- Reading an excel file using Python
- How to generate byte code file in python ?
- Rename all file names in your directory using Python
- Python | Trigonometric operations in excel file using openpyxl
- Python | Writing to an excel file using openpyxl module
- Python | Reading an excel file using openpyxl module
- Python | Arithmetic operations in excel file using openpyxl
- Python program to extract Email-id from URL text file
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.



