Python3 input and output


In the previous chapters, we have actually come into contact with the input and output functions of Python. In this chapter we will introduce the input and output of Python in detail.


Output format beautification

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

The third way is to use the write() method of the file object. The standard output file 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 value.

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

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

  • repr(): Produce an expression that is readable by the interpreter.

For example

>>> s = 'Hello, php'
>>> str(s)
'Hello, php'
>>> repr(s)
"'Hello, php'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'x 的值为: ' + repr(x) + ',  y 的值为:' + repr(y) + '...'
>>> print(s)
x 的值为: 32.5,  y 的值为:40000...
>>> #  repr() 函数可以转义字符串中的特殊字符
... hello = 'hello, php\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, php\n'
>>> # repr() 的参数可以是 Python 的任何对象
... repr((x, y, ('Google', 'php')))
"(32.5, 40000, ('Google', 'php'))"

There 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=' ')
...     # 注意前一行 '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: is in the In one example, spaces between each column are added by print().

This example shows the rjust() method of the string object, which can move the string to the right and fill in spaces on the left.

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

Another method zfill(), which will fill 0s on the left side of the 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('{}网址: "{}!"'.format('php中文网', 'www.php.cn'))
php中文网网址: "www.php.cn!"

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

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

>>> print('{0} 和 {1}'.format('Google', 'php'))
Google 和 php
>>> print('{1} 和 {0}'.format('Google', 'php'))
php 和 Google

If keyword arguments are used in format(), then they The value will point to the parameter using that name.

>>> print('{name}网址: {site}'.format(name='php中文网', site='www.php.cn'))
php中文网网址: www.php.cn

Positional and keyword parameters can be combined in any way:

>>> print('站点列表 {0}, {1}, 和 {other}。'.format('Google', 'php',
                                                       other='Taobao'))
站点列表 Google, php, 和 Taobao。
'!a' (using ascii()), '!s' (using str()) and '!r' (using repr ()) can be used to transform a value before formatting it:
>>> import math
>>> print('常量 PI 的值近似为: {}。'.format(math.pi))
常量 PI 的值近似为: 3.141592653589793。
>>> print('常量 PI 的值近似为: {!r}。'.format(math.pi))
常量 PI 的值近似为: 3.141592653589793。

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

>>> import math
>>> print('常量 PI 的值近似为 {0:.3f}。'.format(math.pi))
常量 PI 的值近似为 3.142。

Passing in an integer after ':' ensures that the field has at least this much width. Useful for beautifying tables.

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

If you have a long format string and you don't want to separate them, it would be nice to format by variable name instead of position.

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

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

The same can also be achieved by using '**' before the table variable Functions:

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

Old-style string formatting

% operator can also implement string formatting. It takes the parameter on the left as a formatted string similar to sprintf(), substitutes the parameter on the right, and returns the formatted string. For example:

>>> import math
>>> print('常量 PI 的值近似为:%5.3f。' % math.pi)
常量 PI 的值近似为:3.142。

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


Reading keyboard input

Python provides The input() function reads a line of text from standard input. The default standard input is the keyboard.

input can receive a Python expression as input and return the result of the operation.

#!/usr/bin/python3

str = input("请输入:");
print ("你输入的内容是: ", str)

This will produce the following results corresponding to the input:

请输入:php中文网
你输入的内容是:  php中文网

Reading and writing files

open() will return a file object, basic syntax The format is as follows:

open(filename, mode)
  • filename: The filename variable is a string value that contains the name of the file you want to access.

  • mode: mode determines the mode of opening the file: read-only, write, append, etc. See the complete list of all possible values ​​below. This parameter is optional and the default file access mode is read-only (r).

Full list of files opened in different modes:

Mode Description
rOpen the file read-only. The file pointer will be placed at the beginning of the file. This is the default mode.
rbOpen a file in binary format for reading only. The file pointer will be placed at the beginning of the file. This is the default mode.
r+Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
rb+Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.
wOpen a file for writing only. If the file already exists, it is overwritten. If the file does not exist, create a new file.
wbOpen a file in binary format for writing only. If the file already exists, it is overwritten. If the file does not exist, create a new file.
w+Open a file for reading and writing. If the file already exists, it is overwritten. If the file does not exist, create a new file.
wb+Open a file in binary format for reading and writing. If the file already exists, it is overwritten. If the file does not exist, create a new file.
aOpen a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, new content will be written after existing content. If the file does not exist, create a new file for writing.
abOpen a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, new content will be written after existing content. If the file does not exist, create a new file for writing.
a+Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file will be opened in append mode. If the file does not exist, a new file is created for reading and writing.
ab+Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, a new file is created for reading and writing.

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

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "w")

f.write( "Python 是一个非常好的语言。\n是的,的确非常好!!\n" )

# 关闭打开的文件
f.close()
  • The first parameter is the name of the file to be opened.

  • The second parameter describes how the file uses characters. mode can be 'r' if the file is read-only, 'w' for writing only (a file with the same name will be deleted if it exists), and 'a' for appending the file contents; any data written will be automatically appended to the end . 'r+' is used for both reading and writing. The mode parameter is optional; 'r' will be the default.

At this time, open the file foo.txt, and the display will be as follows:

$ cat /tmp/foo.txt 
Python 是一个非常好的语言。
是的,的确非常好!!

Methods of the file object

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

f.read()

To read the contents of a file, call f.read(size), which will read a certain number of data, and then as a string or bytes object return.

size is an optional numeric parameter. When size is omitted or negative, then 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

# 打开一个文件
f = open("/tmp/foo.txt", "r")

str = f.read()
print(str)

# 关闭打开的文件
f.close()

Execute the above program, the output result is:

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

f.readline()

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

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "r")

str = f.readline()
print(str)

# 关闭打开的文件
f.close()

Execute the above program, the output result is:

Python 是一个非常好的语言。

f.readlines()

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

If the optional parameter sizehint is set, bytes of the specified length are read and divided into rows.

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "r")

str = f.readlines()
print(str)

# 关闭打开的文件
f.close()

Execute the above program, the output result is:

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

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

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "r")

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

# 关闭打开的文件
f.close()

Execute the above program, output the result For:

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

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

f.write()

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

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "w")

num = f.write( "Python 是一个非常好的语言。\n是的,的确非常好!!\n" )
print(num)
# 关闭打开的文件
f.close()

Execute the above program, the output result is:

29

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

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo1.txt", "w")

value = ('www.php.cn', 14)
s = str(value)
f.write(s)

# 关闭打开的文件
f.close()

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

$ cat /tmp/foo1.txt 
('www.php.cn', 14)

f.tell()

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

f.seek()

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

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


  • ##seek(x,0): Move x characters from the starting position, which is the first character of the first line of the file

  • seek(x,1): Indicates moving backward from the current position x characters

  • seek(-x,2): Indicates moving x characters forward from the end of the file

from_what The value is the default is 0, which is 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)     # 移动到文件的第六个字节
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2) # 移动到文件的倒数第三字节
13
>>> f.read(1)
b'd'


f.close()

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


When you finish 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
<pre>
<p>
当处理一个文件对象时, 使用 with 关键字是非常好的方式。在结束后, 它会帮你正确的关闭文件。 而且写起来也比 try - finally 语句块要简短:</p>
<pre>
>>> with open('/tmp/foo.txt', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

The file object has other methods, such as isatty() and trucate(), but these are generally less used.


pickle module

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

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

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

Basic interface:

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

With the pickle object, the file can be opened in the form of reading:

x = pickle.load(file)

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

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

Instance 1:

#!/usr/bin/python3
import pickle

# 使用pickle模块将数据对象保存到文件
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()

Instance 2:

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

#使用pickle模块从文件中重构python对象
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()