Latest web development tutorials

Python3 input and output

In the first few chapters, we have actually touched Python input and output function. This chapter we will introduce Python specific input and output.


Output format beautify

Python way two output values: expression statements and the print () function.

The third way is to use the file object's write () method, the standard output file can be used sys.stdout reference.

If you want to output in the form of more diverse, you can use str.format () function to format the output value.

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

  • str (): function returns a user readable form of expression.
  • repr (): generates a form of expression interpreter readable.

E.g

>>> s = 'Hello, w3big'
>>> str(s)
'Hello, w3big'
>>> repr(s)
"'Hello, w3big'"
>>> 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, w3big\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, w3big\n'
>>> # repr() 的参数可以是 Python 的任何对象
... repr((x, y, ('Google', 'w3big')))
"(32.5, 40000, ('Google', 'w3big'))"

There are two ways to output a square and cube tables:

>>> 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, the space between each column was added by the print ().

This example shows rjust string object () method, which can be a string to the right, and fill the space on the left.

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

Another method zfill (), it will fill in the left digit 0, as follows:

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

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

>>> print('{}网址: "{}!"'.format('本教程', 'www.w3big.com'))
本教程网址: "www.w3big.com!"

And inside the parentheses characters (called format fields) will be replaced with the format parameter () in.

Position format () in the number in parentheses is used to point the incoming object, as follows:

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

If the keyword argument () in the format, then their value will point to the name of the parameter.

>>> print('{name}网址: {site}'.format(name='本教程', site='www.w3big.com'))
本教程网址: www.w3big.com

Location and keyword arguments can be any combination of:

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

Options ':' followed by the name and format identifier can field. This allows for better value format. The following example will retain the Pi to three decimal places:

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

In ':' after passing an integer, you can at least ensure that there are so many domain width. Useful when used in landscaping form.

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

If you have a long format string, and you do not want to separate them, then when formatting by variable name rather than location would be a good thing.

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

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

You can also use the variable before the table '**' to achieve the same functionality:

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

Old-style string formatting

The% operator can be achieved string formatting. Format string argument to the left as it is similar to sprintf () formula, and the right of substitution, then the returned string formatted example:

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

Because str.format () function is relatively new, most Python code still uses the% operator. However, because this old format will eventually be removed from the language, you should use more str.format ().


Read keyboard input

Python provides the input () function of the input is set to read a line of text from the standard, the default standard input is the keyboard.

input may receive a Python expression as input and returns the result of the operation.

#!/usr/bin/python3

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

This produces the following results corresponding to the input:

请输入:本教程
你输入的内容是:  本教程

Read and write files

open () returns a file object, and basic syntax is as follows:

open(filename, mode)
  • filename: filename variable is a string containing the value you want to access a file name.
  • mode: mode mode determines the open file: Read, Write, appending. See the complete list of all possible values ​​as follows. This non-mandatory parameter, the default file access mode is read-only (r).

Open the complete list of the different modes of file:

mode description
r Open the file in read-only mode. Pointer file will be placed at the beginning of the file. This is the default mode.
rb Open a file for read-only in binary format. Will file pointer at the beginning of the file. This is the default mode.
r + Open a file for reading and writing. Will file pointer at the beginning of the file.
rb + Open a file for reading and writing in binary format. Will file pointer at the beginning of the file.
w Open a file for writing only. If the file already exists it will be overwritten. If the file does not exist, create a new file.
wb Open a file for writing in binary format only. If the file already exists it will be 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 will be overwritten. If the file does not exist, create a new file.
wb + Open a file for reading and writing in binary format. If the file already exists it will be overwritten. If the file does not exist, create a new file.
a Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, after the new content will be written to the existing content. If the file does not exist, create a new file for writing.
ab Open a file for append in binary format. If the file already exists, the file pointer will be placed at the end of the file. In other words, after the new content will be written to the 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. It will append mode the file is opened. If the file does not exist, create a new file for reading and writing.
ab + Open a file for append in binary format. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.

The following examples will be written to the file foo.txt in the string:

#!/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 you want to open.
  • Character second parameter describes how to use the file. mode can be 'r' If the file is read-only, 'w' for only writing (if the file exists it will be deleted), and 'a' for additional file contents; any data written will be automatically added to the end . 'r +' for both read and write. mode argument is optional; 'r' will be the default value.

Opens the file foo.txt, appears as follows:

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

The method of file objects

This example assumes that the remaining section has created a file object called f's.

f.read ()

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

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

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

#!/usr/bin/python3

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

str = f.read()
print(str)

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

The above program, the output is:

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

f.readline ()

f.readline () you read a single line from the file. Newline character '\ n'. f.readline () returns an empty string if, explained that it had been read to the last row.

#!/usr/bin/python3

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

str = f.readline()
print(str)

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

The above program, the output is:

Python 是一个非常好的语言。

f.readlines ()

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

If optional parameters sizehint, then read bytes specified length, and these bytes divided by line.

#!/usr/bin/python3

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

str = f.readlines()
print(str)

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

The above program, the output is:

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

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

#!/usr/bin/python3

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

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

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

The above program, the output is:

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

This method is very simple, but it does not provide a good control. Both because of the different processing mechanism, it is best not to mix.

f.write ()

f.write (string) The string written 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()

The above program, the output is:

29

If you want to write some of the things that is not a string, you will need to be converted:

#!/usr/bin/python3

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

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

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

The above program, open foo1.txt file:

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

f.tell ()

f.tell () returns a file object's position is currently located, it is the number of bytes from the beginning of the file counting.

f.seek ()

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

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

  • seek (x, 0): From the start position, that is the first line of the first character of the file begins to move x characters
  • seek (x, 1): indicates backward movement x characters from the current position
  • seek (-x, 2): shows a mobile x characters from the forward end of the file

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

>>> 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 the text file (not b those open files mode) only with respect to the start of the file to locate.

When you're done with a file, call f.close () to close the file and release system resources, if you try to recall the file, an exception is 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

File object There are other methods, such as isatty () and trucate (), but these are usually less.


pickle module

The python pickle module implements the basic data sequence and deserialization.

We were able to save the serialization operation pickle module target program running information to a file to permanent storage.

By deserialization pickle module, we can create a program to save the object from the file.

Basic Interface:

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

With this object pickle, to be able to open the file as read:

x = pickle.load(file)

Note: Read a string from the file, and the reconstruction of its original python objects.

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

Example 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()

Example 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()