Easy Tutorial
❮ Python Os Popen Ref Math Acosh ❯

Python3 Input and Output

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

#


Output Formatting

Python has two ways to output values: expression statements and the print() function.

A third way is to use the write() method of file objects; the standard output file can be referenced by sys.stdout.

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

If you want to convert the output values into a string, you can use the repr() or str() functions to achieve this.

Example

>>> s = 'Hello, tutorialpro'
>>> str(s)
'Hello, tutorialpro'
>>> repr(s)
"'Hello, tutorialpro'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is: ' + repr(x) + ', and the value of y is: ' + repr(y) + '...'
>>> print(s)
The value of x is: 32.5, and the value of y is: 40000...
>>> # The repr() function can escape special characters in strings
... hello = 'hello, tutorialpro\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, tutorialpro\n'
>>> # repr() can take any Python object as an argument
... repr((x, y, ('Google', 'tutorialpro')))
"(32.5, 40000, ('Google', 'tutorialpro'))"

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' in 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-justifies the string, padding on the left with spaces.

Similar methods include ljust() and center(). These methods do not write anything; they simply return a new string.

Another method is zfill(), which pads a numeric string on the left with zeros. It understands about plus and minus signs:

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

The basic usage of str.format() is as follows:

>>> print('{} website: "{}!"'.format('tutorialpro.org', 'www.tutorialpro.org'))
tutorialpro.org website: "www.tutorialpro.org!"

The brackets and characters within them (called format fields) are replaced with the arguments in format().

The numbers in the brackets are used to refer to the position of the object passed into the format() method, as shown below:

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

If keyword arguments are used in format(), their values are referred to by using the name of the argument.

This is a Chinese to English translation. Here is the English translation of the text:

```python
print('{name} website: {site}'.format(name='tutorialpro.org', site='www.tutorialpro.org'))
tutorialpro.org website: www.tutorialpro.org

Positional and keyword arguments can be combined arbitrarily:

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

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

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

The optional : and format specifier can follow the field name. This allows better formatting of the value. The following example rounds PI to three decimal places:

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

After :, passing an integer ensures that the field has at least that width. Useful for beautifying tables.

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

If you have a long formatted string and you don't want to split it, it's better to use variable names instead of positions during formatting.

The simplest way is to pass a dictionary and use square brackets [] to access the keys:

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

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

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

Old-style String Formatting

The % operator can also be used for string formatting. It treats the left argument as a sprintf()-style format string and substitutes the right arguments into it, then returns the formatted string. For example:

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

Since 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, it is better to use str.format().


Reading Keyboard Input

Python provides the input() built-in function to read a line of text from standard input, which defaults to the keyboard.

Example

#!/usr/bin/python3

str = input("Please enter: ")
print("You entered: ", str)

This will produce the following result corresponding to the input:

Please enter: tutorialpro.org
You entered:  tutorialpro.org

Reading and Writing Files


The open() function will return a file object with the following basic syntax:

open(filename, mode)

Complete list of modes for opening files:

Mode Description
r Opens a file for reading. The file pointer is placed at the beginning of the file. This is the default mode.
rb Opens a file in binary format for reading. The file pointer is placed at the beginning of the file.
r+ Opens a file for both reading and writing. The file pointer is placed at the beginning of the file.
rb+ Opens a file in binary format for both reading and writing. The file pointer is placed at the beginning of the file.
w Opens a file for writing only. If the file already exists, it is opened and truncated to the beginning, removing any existing content. If the file does not exist, a new file is created.
wb Opens a file in binary format for writing only. If the file already exists, it is opened and truncated to the beginning, removing any existing content. If the file does not exist, a new file is created.
w+ Opens a file for both reading and writing. If the file already exists, it is opened and truncated to the beginning, removing any existing content. If the file does not exist, a new file is created.
wb+ Opens a file in binary format for both reading and writing. If the file already exists, it is opened and truncated to the beginning, removing any existing content. If the file does not exist, a new file is created.
a Opens a file for appending. If the file already exists, the file pointer is placed at the end of the file. New content will be written after the existing content. If the file does not exist, a new file is created for writing.
ab Opens a file in binary format for appending. If the file already exists, the file pointer is placed at the end of the file. New content will be written after the existing content. If the file does not exist, a new file is created for writing.
a+ Opens a file for both reading and writing. If the file already exists, the file pointer is placed at the end of the file. The file is opened in append mode. If the file does not exist, a new file is created for reading and writing.
ab+ Opens a file in binary format for appending. If the file already exists, the file pointer is placed at the end of the file. If the file does not exist, a new file is created for reading and writing.

The following table summarizes these modes:

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:

Example

#!/usr/bin/python3

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

f.write("Python is a great language.\nYes, it really is!!\n")

# Close the file
f.close()

At this point, opening the file foo.txt shows the following:

$ cat /tmp/foo.txt 
Python is a great language.
Yes, it really is!!

File Object Methods

The remaining examples in this section assume a file object named f has been created.

f.read()

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

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

The following example assumes the file foo.txt exists (created in the previous example):

Example

#!/usr/bin/python3

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

str = f.read()
print(str)

# Close the file
f.close()

Executing the above program will output:

Python is a great language.
Yes, it really is!!

f.readline()

To read a single line from the file, use f.readline(). This method reads one line at a time. f.readline() reads a single line from the file. The newline character is '\n'. If f.readline() returns an empty string, it indicates that the end of the file has been reached.

Example

#!/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, the output is:

Python is a great language.

f.readlines()

f.readlines() returns all the lines in the file.

If the optional parameter sizehint is set, it reads the specified length of bytes and splits them by lines.

Example

#!/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, the output is:

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

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

Example

#!/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, the output is:

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

This method is simple but does not provide good control. It is best not to mix the two methods due to their different processing mechanisms.

f.write()

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

Example

#!/usr/bin/python3

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

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

Executing the above program, the output is:

29

If you need to write something other than a string, you need to convert it first:

Example

#!/usr/bin/python3

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

value = ('www.tutorialpro.org', 14)
s = str(value)
f.write(s)

# Close the opened file
f.close()

Executing the above program and opening the foo1.txt file:

$ cat /tmp/foo1.txt 
('www.tutorialpro.org', 14)

f.tell()

f.tell() returns the current position of the file object, which is calculated from the beginning of the file.

f.seek()

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

The value of from_what, if 0 means the beginning, 1 means the current position, and 2 means the end of the file, for example:

The default value of from_what is 0, which means 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 byte from the end
13
>>> f.read(1)
b'd'

f.close()

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

After processing a file, call f.close() to close the file and free up system resources. Attempting to call the file again will raise an exception.

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

When processing a file object, using the with keyword is a good approach. It will correctly close the file for you after the operation, and it is shorter than using a try - finally block:

with open('/tmp/foo.txt', 'r') as f:
    read_data = f.read()
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 generally less commonly used.


pickle Module

The pickle module implements basic data serialization and deserialization.

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

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

Basic interface:

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

With the pickle object, you can open the file for reading:

x = pickle.load(file)

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

file: A file-like object that has read() and readline() methods.

Example 1

#!/usr/bin/python3
import pickle

# Using 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()

Example 2

#!/usr/bin/python3
import pprint, pickle

# Using 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()
❮ Python Os Popen Ref Math Acosh ❯