Python3 Input and Output

In the previous chapters, we have actually already touched upon Python's input and output functionality. In this chapter, we will specifically introduce Python's input and output.


Fancier Output Formatting

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

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

If you want more variety in the form of output, 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 user-readable representation.
  • repr():It produces an interpreter-readable representation.

Example

>>> s = 'Hello, Example'
>>> str(s)
'Hello, Example'
>>> repr(s)
"'Hello, Example'"
>>> 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...
>>> # repr() can escape special characters in strings
... hello = 'hello, example\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, example\n'
>>> # The argument of repr() can be any Python object
... repr((x, y, ('Google', 'Example')))
"(32.5, 40000, ('Google', 'Example'))"

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, spaces between columns are added by print().

This example demonstrates the string object's rjust() method, which right-justifies a string and pads spaces on the left.

There are similar methods, such as ljust() and center(). These methods do not write anything; they simply return new strings.

Another method, zfill(), pads zeros on the left of a number, as shown below:

>>> '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('Example Tutorial', 'www.example.com'))
Example Tutorial website:"www.example.com!"

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

Numbers in the brackets are used to refer to the position of the passed-in object in format(), as shown below:

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

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

>>> print('{name} website: {site}'.format(name='Example Tutorial', site='www.example.com'))
Example Tutorial website: www.example.com

Positional and keyword arguments can be combined arbitrarily:

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

!a(Usingascii()), !s(Usingstr()) and!r(Using repr()) can be used to convert a value before formatting it:

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

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

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

In:Passing an integer afterwards ensures that the field is at least that many characters wide. This is useful for making tables look nice.

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

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

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

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

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

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

Old string formatting

%The operator can also perform string formatting. It interprets the left argument as asprintf()-style format string, substitutes the right argument, and then returns the formatted string. For example:

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

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


Reading Keyboard Input

Python providesthe input() built-in functionto read a line of text from standard input; the default standard input is the keyboard.

Example

#!/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: Example  
The content you entered is: Example

Reading and Writing Files

In Python, file operations are done through theopen()function. This function returns a file object for subsequent reading or writing operations.

open()The basic syntax is as follows:

open(filename, mode)
  • filename:The path (string) of the file to access.
  • mode:The file opening mode, used to specify how to read or write (such as read-only, write, append, etc.). This parameter is optional, with the default valuer(read-only).

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

Mode Description
r Opens the file in read-only mode (default mode). The file must exist, and the file pointer is at the beginning.
rb Opens the file in binary format for read-only access (such as images, videos, etc.). The file pointer is at the beginning.
r+ Opens the file in read-write mode. 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 betruncated; if it does not exist, a new file will be created.
wb Opens the file in binary format for write-only. If the file exists, it will be truncated; if it does not exist, a new file will be created.
w+ Opens the file in read-write mode. If the file exists, it will be truncated; if it does not exist, a new file will be created.
wb+ Opens the file in binary format for reading and writing. If the file exists, it will be truncated; if it does not exist, a new file will be created.
a Opens the file in append mode. If the file exists, written content will be appended to the end; if it does not exist, a new file will be created.
ab Opens the file in binary format for appending. Written content will be appended to the end; if it does not exist, a new file will be created.
a+ Opens the file in read-write mode. The file pointer is at the end by default (append mode); if it does not exist, a new file will be 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 will be created.

Explanation:Addingbafter the mode means operating on the file in binary mode, often used for processing non-text files such as 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:

Example

#!/usr/bin/python3

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

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

# Close the opened file
f.close()
  • The first argument is the name of the file to be opened.
  • The second parameter describes how the file will be used. mode can be 'r' if the file is read-only, 'w' only for writing (an existing file with the same name will be deleted), and 'a' for appending to the file; 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 是一个非常好的语言。
是的,的确非常好!!

Methods of File Objects

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

f.read()

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

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

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

Example

#!/usr/bin/python3

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

str = f.read()
print(str)

# Close the opened file
f.close()

After executing the above program, the output is:

Python 是一个非常好的语言。
是的,的确非常好!!

f.readline()

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.

Example

#!/usr/bin/python3

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

str = f.readline()
print(str)

# Close the opened file
f.close()

After executing the above program, the output is:

Python 是一个非常好的语言。

f.readlines()

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

If the optional parameter sizehint is set, it reads the specified length of bytes and splits these bytes 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()

After executing the above program, the output is:

['Python 是一个非常好的语言。\n', '是的,的确非常好!!\n']

Another way is to iterate over a file object and then 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()

After executing the above program, the output is:

Python 是一个非常好的语言。
是的,的确非常好!!

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

f.write()

f.write(string) writes string to the file, and then 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 very good language.\nYes, it is indeed very good!!\n" )
print(num)
# Close the opened file
f.close()

After executing the above program, the output is:

29

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

Example

#!/usr/bin/python3

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

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

# Close the opened file
f.close()

After executing the above program, open the foo1.txt file:

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

f.tell()

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-number offset from the beginning of the file. f.tell() returns an integer indicating the current position of the file pointer.

f.seek()

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 the specified position.

offset represents the offset relative to the whence parameter. The value of from_what: if it is 0, it means the beginning; if it is 1, it means the current position; 2 means the end of the file. For example:

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

The default value of from_what is 0, i.e., the beginning of the file. A complete example is given below:

>>> 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 of the file
13
>>> f.read(1)
b'd'

f.close()

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

When you have finished processing a file, call f.close() to close the file and release the system's 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 close the file correctly for you. It is also shorter to write than a try-finally statement 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.


The pickle Module

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 a 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 a file.

Basic interface:

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

With this pickle object, you can open the file in read mode:

x = pickle.load(file)

Note:Read a string from the file and reconstruct it into the original Python object.

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

Example 1

#!/usr/bin/python3
import pickle

# Use the pickle module to save the data object 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

# Use the pickle module to reconstruct the Python object 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()
Other extensions