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).
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.
Output (in “samplefile.txt”) :
Note : Try this in interpreter on your system, since such file can’t be accessed on Online IDE.
- Python end parameter in print()
- Python | sep parameter in print()
- Python | Key-Value to URL Parameter Conversion
- Use of na_values parameter in read_csv() function of Pandas in Python
- Python | Split and Pass list as separate parameter
- Python program to reverse the content of a file and store it in another file
- reStructuredText | .rst file to HTML file using Python for Documentations
- Create a GUI to convert CSV file into excel file using Python
- Python - Get file id of windows file
- Positional-only Parameter in Python3.8
- Reading Python File-Like Objects from C | Python
- Mahotas - Parameter-Free Threshold Adjacency Statistics
- File Searching using Python
- File Objects in Python
- Writing to file in Python
- Open a File in Python
- Python append to a file
- File Handling in Python
- Python | Kivy .kv 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 email@example.com. 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.