Python file parameter in print()?


The regular use of the print() function is to display text either in the command-line or in the interactive interpreter. But the same function can also write into a file or an output stream.

Printing to file

In the example we can open a file with a new filename in write mode then mention that filename in the print function. The value to be written to the file can be passed as arguments into the print function.

Example

Newfile= open("exam_score.txt", "w")

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

print(exam_name, exam_date, exam_score, file=Newfile , sep = ",")

# close the file
Newfile.close()

Output

Running the above code gives us a file named exam_scores.txt with the following content.

Degree,2-Nov,323

Printing to standard output

We can also use print() to print ot the standard output or standard error.

Example

import sys
Newfile= open("exam_score.txt", "w")

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

print(exam_name, exam_date, exam_score, file=sys.stderr, sep = ",")

# close the file
Newfile.close()

Output

Running the above code gives us the following result −

Degree,2-Nov,323

Updated on: 12-Jan-2021

683 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements