Python file parameter in print()?

The print() function in Python can write text to different destinations using the file parameter. By default, print() outputs to the console, but you can redirect it to files or other output streams.

Syntax

print(*values, file=file_object, sep=' ', end='\n', flush=False)

The file parameter accepts any object with a write() method, such as file objects, sys.stdout, or sys.stderr.

Printing to a File

You can write directly to a file by opening it in write mode and passing the file object to the file parameter ?

# Open file in write mode
with open("exam_score.txt", "w") as newfile:
    # Variables
    exam_name = "Degree"
    exam_date = "2-Nov"
    exam_score = 323
    
    print(exam_name, exam_date, exam_score, file=newfile, sep=",")

# Read and display the file content
with open("exam_score.txt", "r") as f:
    print("File content:", f.read().strip())
File content: Degree,2-Nov,323

Printing to Standard Error

You can redirect output to standard error stream using sys.stderr ?

import sys

# Variables
exam_name = "Degree"
exam_date = "2-Nov"
exam_score = 323

# Print to standard error
print(exam_name, exam_date, exam_score, file=sys.stderr, sep=",")

# Print to standard output for comparison
print("This goes to standard output")
Degree,2-Nov,323
This goes to standard output

Multiple Print Statements to Same File

You can write multiple lines to the same file by keeping it open ?

with open("students.txt", "w") as file:
    print("Student Name", "Subject", "Score", file=file, sep="\t")
    print("Alice", "Math", 95, file=file, sep="\t")
    print("Bob", "Science", 87, file=file, sep="\t")
    print("Carol", "English", 92, file=file, sep="\t")

# Read and display the file
with open("students.txt", "r") as f:
    print("File contents:")
    print(f.read())
File contents:
Student Name	Subject	Score
Alice	Math	95
Bob	Science	87
Carol	English	92

Comparison of Output Destinations

Destination Parameter Use Case
Console (default) file=sys.stdout Regular program output
File file=file_object Logging, data export
Standard Error file=sys.stderr Error messages, debugging

Conclusion

The file parameter in print() allows you to redirect output to files or different streams. Use with statements for proper file handling and sys.stderr for error messages.

Updated on: 2026-03-15T18:37:37+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements