file parameter in Python with print() function

Python | file parameter in print(): In this tutorial, we are going to learn about the file parameter with print() function, how does it work with print() function? By IncludeHelp Last updated : December 17, 2023

The 'file' parameter in printf() function

'file' parameter is used with print() function to write the value of given arguments to the specified file. If it is not specified, by default the value is written to system.stdout.

It can be used to create log the values i.e. to keep the track to the statements, logics, etc.

We can use two ways,

  1. Writing to the sys.stderr
  2. Writing to the external file

Note: "file" is available in Python 3.x or later versions.

Syntax

print(argument1, argument2, ..., file = value)

Examples

Example 1: Printing to stderr

# Python code for printing to stderr

# importing the package
import sys # for sys.stderr

# variables
name = "Mike"
age = 21
city = "Washington, D.C."

print("printing to stderr...")
print(name, age, city, file=sys.stderr)

Output

printing to stderr...
Mike 21 Washington, D.C.

Note: In the output, "printing to stderr..." will be printed as standard output and "Mike 21 Washington, D.C." will be printed as error.

Example 2: Printing to an external file

# Python code for printing to file

# open the file in write mode
obj_file = open("logs.txt", "w")

# variables
name = "Mike"
age = 21
city = "Washington, D.C."

print("printing to a file...")
print(name, age, city, file=obj_file)

# closing the file
obj_file.close()

Output

printing to a file...

logs.txt:

Mike 21 Washington, D.C.

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.