Skip to content

Python3 Input and Output

In the previous chapters, we have already encountered Python’s input and output functionality. This chapter will specifically introduce Python’s input and output.


Python has two ways of outputting values: expression statements and the print() function.

The third way is to use the write() method of file objects, where the standard output file can be referenced using sys.stdout.

If you want more diverse output forms, you can use the str.format() function to format output values.

If you want to convert output values to strings, you can use the repr() or str() functions.

  • str(): The function returns a human-readable representation.
  • repr(): Produces an interpreter-readable representation.
>>> s = 'Hello, Runoob'
>>> str(s)
'Hello, Runoob'
>>> repr(s)
"'Hello, Runoob'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is: ' + repr(x) + ',  the value of y is: ' + repr(y) + '...'
>>> print(s)
The value of x is: 32.5,  the value of y is: 40000...
>>> #  The repr() function can escape special characters in strings
... hello = 'hello, runoob\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, runoob\n'
>>> # The argument of repr() can be any Python object
... repr((x, y, ('Google', 'Runoob')))
"(32.5, 40000, ('Google', 'Runoob'))"

Here are two ways to output a table of squares and cubes:

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # Note the use of 'end' on the previous line
...     print(repr(x*x*x).rjust(4))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

>>> for x in range(1, 11):
...     print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

Note: In the first example, the spaces between columns are added by print().

This example demonstrates the rjust() method of string objects, which right-aligns the string and pads the left side with spaces.

There are also similar methods like ljust() and center(). These methods do not write anything; they merely return a new string.

Another method, zfill(), pads the left side of a number with 0s, as shown below:

>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'

Basic usage of str.format() is as follows:

>>> print('{} URL: "{}!"'.format('Runoob Tutorial', 'www.runoob.com'))
Runoob Tutorial URL: "www.runoob.com!"

The brackets and the characters inside them (called format fields) will be replaced by the arguments in format().

The numbers in the brackets are used to point to the object’s position in format(), as shown below:

>>> print('{0} and {1}'.format('Google', 'Runoob'))
Google and Runoob
>>> print('{1} and {0}'.format('Google', 'Runoob'))
Runoob and Google

If keyword arguments are used in format(), their values will point to the argument using that name.

>>> print('{name} URL: {site}'.format(name='Runoob Tutorial', site='www.runoob.com'))
Runoob Tutorial URL: www.runoob.com

Positional and keyword arguments can be combined arbitrarily:

>>> print('Site list {0}, {1}, and {other}.'.format('Google', 'Runoob', other='Taobao'))
Site list Google, Runoob, and Taobao.

!a (using ascii()), !s (using str()) and !r (using repr()) can be used to transform a value before formatting it:

>>> import math
>>> print('The value of the constant PI is approximately: {}.'.format(math.pi))
The value of the constant PI is approximately: 3.141592653589793.
>>> print('The value of the constant PI is approximately: {!r}.'.format(math.pi))
The value of the constant PI is approximately: 3.141592653589793.

The optional : and format specifier can follow the field name. This allows for better formatting of values. The following example keeps Pi to three decimal places:

>>> import math
>>> print('The value of the constant PI is approximately {0:.3f}.'.format(math.pi))
The value of the constant PI is approximately 3.142.

Passing an integer after : ensures that the field is at least that many characters wide. This is useful for beautifying tables.

>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
>>> for name, number in table.items():
...     print('{0:10} ==> {1:10d}'.format(name, number))
... 
Google     ==>          1
Runoob     ==>          2
Taobao     ==>          3

If you have a very long format string and you don’t want to split it, it’s a good idea to format by variable name rather than position.

The simplest approach is to pass in a dictionary and use square brackets [] to access the key values:

>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
>>> print('Runoob: {0[Runoob]:d}; Google: {0[Google]:d}; Taobao: {0[Taobao]:d}'.format(table))
Runoob: 2; Google: 1; Taobao: 3

You can also achieve the same functionality by using ** before the table variable:

>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
>>> print('Runoob: {Runoob:d}; Google: {Google:d}; Taobao: {Taobao:d}'.format(**table))
Runoob: 2; Google: 1; Taobao: 3

The % operator can also achieve string formatting. It takes the left argument as a format string similar to sprintf(), substitutes the right argument, and returns the formatted string. For example:

>>> import math
>>> print('The value of the constant PI is approximately: %5.3f.' % math.pi)
The value of the constant PI is approximately: 3.142.

Because str.format() is a newer function, most Python code still uses the % operator. However, since this old-style formatting will eventually be removed from the language, you should use str.format() more often.


Python provides the input() built-in function to read a line of text from standard input. The default standard input is the keyboard.

#!/usr/bin/python3

str = input("Please enter:");
print ("The content you entered is: ", str)

This produces the following result corresponding to the input:

Please enter:Runboo Tutorial
The content you entered is:  Runoob Tutorial

In Python, file operations are completed through the open() function. This function returns a file object for subsequent read or write operations.

The basic syntax of open() is as follows:

open(filename, mode)
  • filename: The path to the file to be accessed (string).
  • mode: The file open mode, used to specify the read/write method (e.g., read-only, write, append). This parameter is optional, with a default value of r (read-only).

Common file open modes are as follows (it is recommended to focus on r / w / a):

Mode Description
r Opens the file in read-only mode (default). The file must exist, and the file pointer is at the beginning.
rb Opens the file in binary format for read-only (e.g., images, videos). The file pointer is at the beginning.
r+ Opens the file for reading and writing. The file must exist, and the file pointer is at the beginning.
rb+ Opens the file in binary format for reading and writing. The file pointer is at the beginning.
w Opens the file in write-only mode. If the file exists, it will be cleared; if it does not exist, a new file is created.
wb Opens the file in binary format for write-only. If the file exists, it will be cleared; if it does not exist, a new file is created.
w+ Opens the file for reading and writing. If the file exists, it will be cleared; if it does not exist, a new file is created.
wb+ Opens the file in binary format for reading and writing. If the file exists, it will be cleared; if it does not exist, a new file is created.
a Opens the file in append mode. If the file exists, written content is appended to the end; if it does not exist, a new file is created.
ab Opens the file in binary format for append. Written content is appended to the end; if it does not exist, a new file is created.
a+ Opens the file for reading and writing. The file pointer is at the end by default (append mode); if it does not exist, a new file is created.
ab+ Opens the file in binary format for reading and writing. The file pointer is at the end by default; if it does not exist, a new file is created.

Note: Adding b after the mode indicates operating on the file in binary mode, commonly used for non-text files like images and audio.

The following diagram summarizes these modes well:

Mode r r+ w w+ a a+
Read + + + +
Write + + + + +
Create + + + +
Overwrite + +
Pointer at start + + + +
Pointer at end + +

The following example writes a string to the file foo.txt:

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "w")

f.write( "Python is a very good language.\nYes, it is indeed very good!!\n" )

# Close the opened file
f.close()
  • The first parameter is the name of the file to open.
  • The second parameter describes how the file will be used. mode can be ‘r’ if the file is read-only, ‘w’ for write-only (if a file with the same name exists, it will be deleted), and ‘a’ for appending file content; any data written will be automatically added to the end. ‘r+’ is for both reading and writing. The mode parameter is optional; ‘r’ will be the default value.

At this point, open the file foo.txt, which displays as follows:

$ cat /tmp/foo.txt 
Python is a very good language.
Yes, it is indeed very good!!

The remaining examples in this section assume that a file object called f has already been created.

To read the contents of a file, call f.read(size), which reads a certain amount of data and returns it as a string or bytes object.

size is an optional numeric parameter. When size is omitted or negative, the entire contents of the file will be read and returned.

The following example assumes that the file foo.txt already exists (created in the above example):

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "r")

str = f.read()
print(str)

# Close the opened file
f.close()

Executing the above program produces the following output:

Python is a very good language.
Yes, it is indeed very good!!

f.readline() reads a single line from the file. The newline character is ‘\n’. If f.readline() returns an empty string, it means the last line has already been read.

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "r")

str = f.readline()
print(str)

# Close the opened file
f.close()

Executing the above program produces the following output:

Python is a very good language.

f.readlines() will return all lines contained in the file.

If the optional parameter sizehint is set, it reads the specified number of bytes and splits these bytes into lines.

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "r")

str = f.readlines()
print(str)

# Close the opened file
f.close()

Executing the above program produces the following output:

['Python is a very good language.\n', 'Yes, it is indeed very good!!\n']

Another way is to iterate over a file object and read each line:

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "r")

for line in f:
    print(line, end='')

# Close the opened file
f.close()

Executing the above program produces the following output:

Python is a very good language.
Yes, it is indeed very good!!

This method is simple, but it does not provide very good control. Because the processing mechanisms are different, it is best not to mix them.

f.write(string) writes the string to the file and returns the number of characters written.

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "w")

num = f.write( "Python is a very good language.\nYes, it is indeed very good!!\n" )
print(num)
# Close the opened file
f.close()

Executing the above program produces the following output:

29

If you want to write something that is not a string, you will need to convert it first:

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo1.txt", "w")

value = ('www.runoob.com', 14)
s = str(value)
f.write(s)

# Close the opened file
f.close()

Executing the above program, open the foo1.txt file:

$ cat /tmp/foo1.txt 
('www.runoob.com', 14)

f.tell() is used to return the current read/write position of the file (i.e., the position of the file pointer). The file pointer represents the byte offset from the beginning of the file. f.tell() returns an integer indicating the current position of the file pointer.

If you want to change the current position of the file pointer, you can use the f.seek(offset, from_what) function.

f.seek(offset, whence) is used to move the file pointer to a specified position.

offset represents the offset relative to the whence parameter. The value of from_what, if 0, indicates the beginning, if 1 indicates the current position, and 2 indicates the end of the file, for example:

  • seek(x,0): Move x characters from the starting position, i.e., the first character of the first line of the file
  • seek(x,1): Move x characters backward from the current position
  • seek(-x,2): Move x characters backward from the end of the file

The default value of from_what is 0, i.e., the beginning of the file. Here is a complete example:

>>> f = open('/tmp/foo.txt', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)     # Move to the sixth byte of the file
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2) # Move to the third last byte of the file
13
>>> f.read(1)
b'd'

In text files (those opened without b in the mode), positioning is only relative to the beginning of the file.

When you have finished processing a file, call f.close() to close the file and release system resources. If you try to call the file again, an exception will be thrown.

>>> f.close()
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file

When dealing with a file object, using the with keyword is a very good approach. After it finishes, it will correctly close the file for you. It is also shorter to write than a try - finally block:

>>> with open('/tmp/foo.txt', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

File objects have other methods, such as isatty() and truncate(), but these are usually less commonly used.


Python’s pickle module implements basic data serialization and deserialization.

Through the serialization operation of the pickle module, we can save the object information running in the program to a file for permanent storage.

Through the deserialization operation of the pickle module, we can recreate the objects saved by the previous program from the file.

Basic interface:

pickle.dump(obj, file, [,protocol])

With the pickle object, the file can be opened in read mode:

x = pickle.load(file)

Note: Reads a string from the file and reconstructs it into the original Python object.

file: A file-like object with read() and readline() interfaces.

#!/usr/bin/python3
import pickle

# Use the pickle module to save data objects to a file
data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}

selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)

output = open('data.pkl', 'wb')

# Pickle dictionary using protocol 0.
pickle.dump(data1, output)

# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)

output.close()
#!/usr/bin/python3
import pprint, pickle

# Use the pickle module to reconstruct Python objects from a file
pkl_file = open('data.pkl', 'rb')

data1 = pickle.load(pkl_file)
pprint.pprint(data1)

data2 = pickle.load(pkl_file)
pprint.pprint(data2)

pkl_file.close()