Python3 input and output

May 10, 2021 03:00 Python3

Table of contents

In the previous chapters, we've actually come into contact with the functionality of Python's input and output. In this section we will cover the input and output of Python in detail.

The output format is beautified

Python outputs values in two ways: expression statements and print() functions. ( The third way is to use the write() method of the file object; S tandard output files can be referenced with sys.stdout. )

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

If you want to convert the output value into a string, you can do so using the repr() or str() functions.

The str() function returns a user-readable expression.

Repr() produces an interpreter-readable expression.

For example

>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1/7)
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print(s)
The value of x is 32.5, and y is 40000...
>>> #  repr() 函数可以转义字符串中的特殊字符
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # repr() 的参数可以是 Python 的任何对象
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"

There are two ways to output a squared and cubic table:

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # 注意前一行 'end' 的使用
...     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 shows the rjust() method of a string object, which can place the string to the right and fill in spaces on the left.

There are similar methods, such as ljust() and center(). These methods don't write anything, they just return a new string.

Another method, zfill(), fills 0 on the left side of the number, as follows:

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

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

>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"

Parenthesis and the characters inside it (called formatted fields) are replaced by parameters in format().

The numbers in parentheses are used to point to the position of the incoming object in format(), as follows:

>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam

If keyword parameters are used in format(), their values point to parameters that use the name.

>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.

Location and keyword parameters can be combined at will:

>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',other='Georg'))
The story of Bill, Manfred, and Georg.

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

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

Optional ':' and format identifiers can be followed by field names. T his allows for better formatting of values. T he following example keeps Pi three places behind the point of the count:

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

After ':', an integer is passed in to ensure that the field has at least so much width. U seful for beautifying tables.

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...     print('{0:10} ==> {1:10d}'.format(name, phone))
Jack       ==>       4098
Dcab       ==>       7678
Sjoerd     ==>       4127

If you have a very long formatted string and you don't want to separate them, it's good to pass the variable name instead of the location when formatting.

The simplest is to pass in a dictionary, and then use the square bracket '''' to access the key value:

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
          'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

You can also do the same by using '''' before the table variable:

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

Legacy string formatting

The % operator can also implement string formatting. I t treats the parameters on the left as a formatted string similar to sprintf() and replaces the right, and then returns the formatted string. F or example:

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

Because str.format() is a newer function, most Python code still uses the % operator. B ut since this old formatting will eventually be removed from the language, str.format() should be used more.

Read and write files

open() returns a file object in the following basic syntax format:

open(filename, mode)


>>> f = open('/tmp/workfile', 'w')
  • The first argument is the name of the file to open.
  • The second parameter describes how the characters are used by the file. m ode can be 'r' if the file is read-only, 'w' is only used for writing (which will be deleted if a file with the same name exists), and 'a' is used to append the contents of the file; A ny data written is automatically added to the end. ' r-plus' is also used for reading and writing. T he mode parameter is optional;

The method of the file object

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

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

size is an optional number type parameter. When size is ignored or negative, everything in the file is read and returned.

'This is the entire file.\n'


f.readline() reads a separate line from the file. T he line break is ''n'. f.readline() If an empty string is returned, the last line has been read.

>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()


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

If you set the optional parameter sizehint, read the bytes of the specified length and split them in rows.

>>> f.readlines()
['This is the first line of the file.\n', 'Second line of the file\n']

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

>>> for line in f:
...     print(line, end='')
This is the first line of the file.
Second line of the file

This method is simple, but does not provide a good control. B ecause the two handle different mechanisms, it is best not to mix.


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

>>> f.write('This is a test\n')

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

>>> value = ('the answer', 42)
>>> s = str(value)
>>> f.write(s)


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

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

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

  • seek(x, 0): Moves x characters from the starting position, which is the first character on the first line of the file
  • seek(x, 1): represents moving x characters back from the current position
  • seek (-x, 2): represents moving x characters forward from the end of the file

from_what value is 0 by default, which is the beginning of the file. Here's a complete example:

>>> f = open('/tmp/workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
>>>     # 移动到文件的第六个字节
>>>, 2) # 移动到文件的倒数第三字节


In text files (those that do not have b in open file mode), they are positioned only relative to the starting position of the file.

When you have processed a file, call f.close() to close the file and free up resources for the system, and if you try to call the file again, an exception is thrown.

>>> f.close()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file
当处理一个文件对象时, 使用 with 关键字是非常好的方式。在结束后, 它会帮你正确的关闭文件。 而且写起来也比 try - finally 语句块要简短:</p>
>>> with open('/tmp/workfile', 'r') as f:
...     read_data =
>>> f.closed

File objects have other methods, such as isatty() and trucate(), but these are usually less useful.

Pickle module

Python's pickle module enables basic data sething and reseerication.

Through the serialization operation of the pickle module, we are able to save the object information running in the program to the file and store it permanently.

With the pickle module's anti-serialization operation, we were able to create the last program-saved object from the file.

Basic interface:

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

With pickle, the file can be opened as a read:

x = pickle.load(file)

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

file: Class file objects with read() and readline() interfaces.

Example 1:


import pickle

data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}

selfref_list = [1, 2, 3]

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)


Example 2:


import pprint, pickle

pkl_file = open('data.pkl', 'rb')

data1 = pickle.load(pkl_file)

data2 = pickle.load(pkl_file)