Open In App

file parameter of Python’s print() Function

Improve
Improve
Like Article
Like
Save
Share
Report

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).

Python3




# Code for printing to STDERR
import sys
 
print('GeeksForGeeks', file = sys.stderr)


Output :

GeeksForGeeks

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.

Python3




# Code for printing to a file
sample = open('samplefile.txt', 'w')
 
print('GeeksForGeeks', file = sample)
sample.close()


Output (in “samplefile.txt”)

GeeksForGeeks

Note: Try this in interpreter on your system, since such file can’t be accessed on Online IDE.

Advanced usage examples

The “print()” function is very convenient for writing some text to external files. We can even combine it with string methods available in python. This section presents some examples to demonstrate the same. Moreover, we use the “with” syntax to open the file in this section. This ensures that the file is closed properly automatically either when some error occurs or when the with block is exit. Here is the syntax to open files with “withblock –

with open("<path to file>", "<open-mode>") as f:
# f is the file pointer inside this block, one can use any other variable name too
# do all the operations with the file in this block
# file closed automatically here as with block exits

Example 1: Writing table of a number to an external file using print()

Here we use the “string.format()” method inside print function to write table of five to the file “sampleFile.txt”.

Python3




with open('sampleFile.txt', 'w') as f:
    for i in range(1,11):
        print('{} x {} = {}'.format(5, i, 5*i), file = f)


Output of sampleFile.txt

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

The file is opened in write mode (w). Each time the print function is executed, it appends the output to the file represented by file pointer f. The output is same as what it would have looked on monitor.

Example 2: Writing data (2d-table) to an external file using print()

If we have a 2d list containing data like this –

# fruit name, fruit color, price
data = [
["Orange", "Orange", 50],
["Apple", "Red", 80],
["Banana", "Yellow", 40]
]

We can easily write it to a file say “dataFile.txt” with this code –

Python3




# fruit name, fruit color, price
data = [
    ["Orange", "Orange", 50],
    ["Apple", "Red", 80],
    ["Banana", "Yellow", 40]
]
 
with open('dataFile.txt', 'w') as f:
    for row in data:
        print(*row, file = f)


Output of dataFile.txt

Orange Orange 50
Apple Red 80
Banana Yellow 40

The ‘*’ character is used to spread the element of the list stored in row as positional arguments to print.

Example 3: Writing data (2d-table) to an external file using print() in a pretty manner

The output of the last example is not formatted properly and hence less readable to human eyes. In this example, we add headers and format it with the “string.format” method. Here is the code –

Python3




# fruit name, fruit color, price
data = [
    ["Orange", "Orange", 50],
    ["Apple", "Red", 80],
    ["Banana", "Yellow", 40]
]
 
with open('dataFile.txt', 'w') as f:
    # defining a line string
    line = "+" + "-"*12 + "+" + "-"*12 + "+" + "-"*7 + "+"
 
    # printing headers
    print(line, file = f)
    print("| {:>10s} | {:>10s} | {:>5s} |".format('Fruit', 'Color', 'Price'), file = f)
    print(line, file = f)
 
    # printing data
    for row in data:
        print("| {:>10s} | {:>10s} | {:>5d} |".format(row[0],row[1],row[2]), file = f)
    print(line, file = f)


Output of “dataFile.txt”

+------------+------------+-------+
| Fruit | Color | Price |
+------------+------------+-------+
| Orange | Orange | 50 |
| Apple | Red | 80 |
| Banana | Yellow | 40 |
+------------+------------+-------+

Now, the output looks better, isn’t it? We just used the format function to describe the spacing and formatting of the data. Describing the format function is out of the scope of this article though. Moreover, we use a string saved in variable name line and print it wherever we want a line.

Example 4: Writing a csv file using python print() function

A csv file (comma separated values file) is simply a text file ending in “.csv” extension representing 2-dimensional data in which each line represents a separate row, and the entries of a row are separated by comma. Writing the above data to a csv file say “dataFile.csv” is as simple as this code –

Python3




# fruit name, fruit color, price
data = [
    ["Orange", "Orange", 50],
    ["Apple", "Red", 80],
    ["Banana", "Yellow", 40]
]
 
# writing the csv file
with open('dataFile.csv', 'w') as f:
    for row in data:
        print(*row, sep = ',', end = '\n', file = f)


Output of “dataFile.csv”

Orange,Orange,50
Apple,Red,80
Banana,Yellow,40


Last Updated : 27 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads