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?
Submitted by IncludeHelp, on June 14, 2020

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.


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

Python examples with 'file' parameter in print()

Example 1: Printing to stderr

# Python code for printing to stderr

# imprting 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)


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


printing to a file...


Mike 21 Washington, D.C.

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.