Python programming (6)

zhaozj2021-02-08  212

Chapter 7 Input Output

There are several ways to output from programs; data can be displayed in readable form, or saved to files for future use. This chapter discusses some ways to input and output.

7.1 Output format control

We have seen two output values: Expressions and Print statements. (The third method is to use the write () method of the file object, the standard output file can be referenced by sys.stdout. See the library reference manual).

We often need to control the output format, not just a value separated by space. There are two ways to control the output format: one way is to conduct string processing, with a piece of string and merge operations that can be imagined. The standard module string contains useful operations such as populating strings to the specified column width, followed by mention.

Another way is to use the% operator. This operator calculates the left transport with a string, which is converted to the Right operation calculation element into a string according to the Sprintf () function format of C to return the conversion result.

The problem is: How to convert the value to a string?

Fortunately, Python has a way to convert any value to a string: use the REPR () function, or write the value between two reverse quotes (``). E.g:

>>> x = 10 * 3.14

>>> Y = 200 * 200

>>> s = 'The value of x is' `x` ', and y is' ` y` '...'

>>> Print S

The value of x is 31.4, and y is 40000 ...

>>> # reverse quotes also apply to non-numerical types

... p = [x, y]

>>> PS = REPR (P)

>>> PS

'[31.4, 40000]'

>>> # 转 转 字串 对 字 字 字 字 引 引 引 引 引 引

... Hello = 'Hello, World / N'

>>> Hellos = `Hello`

>>> Print Hellos

'Hello, World / 012'

>>> # In-reverse quotation marks can be a preface table

... `x, y, ('spam', 'eggs')`

"(31.4, 40000, ('spam', 'eggs'))"

Below is two ways to write square, cube:

>>> Import String

>>> for x in Range (1, 11):

... Print String.rjust (`x`, 2), string.rjust (` x * x`, 3),

... # 前 行 结 表示 不 行 行

... Print String.rjust (`x * x * x`, 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 '% 2D% 3D% 4D'% (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 that the items between the print output have an additional space, which is the provisions of Print.

This example shows the usage of the function string.rjust (). This function can put a string into the specified width right alignment, and the left space is filled with the left. Similar functions are String.ljust () and String.center (). These functions do not output out, just return the conversion string. If the input string is too long, it will not be truncated but is returned. Such processing may make your column to fail, but this may be better than truncation, the result of the truncation is what we see an error. (If you really need to truncate, you can always add a piece of fragment, such as string.ljust (x, n) [0: n]).

There is also a function string.zfill (), which can be filled with the left side. This function can handle the case with a decline:

>>> String.ZFILL ('12 ', 5)

'00012'

>>> String.ZFILL ('- 3.14', 7)

'-003.14'

>>> String.ZFILL ('3.14159265359, 5)

'3.14159265359'

The usage of% operator is as follows:

>>> Import Math

>>> Print 'The value of pi is approximately% 5.3f.'% Math.pi

The value of pi is approximately 3.142.

If there are multiple values ​​to be given in a program, there are multiple formats in the format string, such as:

>>> Table = {'Sjoerd': 4127, 'Jack': 4098, 'DCAB': 8637678}

>>> for Name, Phone in Table.Items ():

... Print '% - 10S ==>% 10D'% (Name, Phone)

...

Jack ==> 4098

DCAB ==> 8637678

Sjoerd ==> 4127

Most formats are the same as C usage, requiring the value of the value to be output, in line with the needs of the format. However, if you don't trigger an exception error, you will not produce the kernel column. Python's% s format is much wide: if the corresponding output item is not a string object, you will turn it into a string with the STR () built-in function. In the format specified, the width is specified as a * number indicating that the integer of the specified width in the output item. C Format% N and% P are not supported.

If you have a long format string, you don't want to separate it, you can specify the name in the specified format, so you don't need to put the format and the name, this format is "% (variable name) format, for example::

>>> Table = {'Sjoerd': 4127, 'Jack': 4098, 'DCAB': 8637678}

>>> Print 'Jack:% (JACK) D; Sjoerd:% (SJOERD) D; DCAB:% (DCAB) D'% TableJack: 4098; Sjoerd: 4127; DCAB: 8637678

Here the output is always a dictionary, the value of the dictionary is the value to output, the key value of the dictionary is the name of each value. This output format is often used in conjunction with the built-in function var (), and var () returns a dictionary containing all local variables.

7.2 read and write files

Open () Opens a file object, often uses two parameters: "Open (file name, mode)". E.g:

>>> f = Open ('/ tmp / workfile', 'w')

>>> Print F

The first index is a string containing the file name, and the second independent variable is a string of file open mode. Mode 'R' represents reading, 'W' means that only written (existing same name file is cleared), 'a' indicates that the open file is added, 'R ' indicates that the open file can be read or written. Open mode parameter is optional, default is 'r' mode.

Add 'b' in WINDOWS and Macintosh in the mode to open files in binary format, such as 'RB', 'WB', 'R B'. Windows has different processing for text files and binaries, and the wrap characters in the text file change when reading and writing. This modification of the file data does not affect the ASCII text file, but the binary data such as the JPEG or ".exe" file will undermine. Reading and writing This file must use a binary format. (The precise description of the text mode in Macintosh depends on the C library used).

7.2.1 Method for file object

An example behind this section assumes a file object called F.

To read the file content, invoke F.Read (size), you can read the data of a certain number of bytes to return to a string. SIZE is an optional value parameter, omitted Size or Size to read the entire file and return to a string; if the file is doubled than your machine, it is your problem. Read more when you specify the positive size and return to the size byte. If the file end is read, F.Read () returns an empty string (""). Such as:

>>> F.Read ()

'This is the entire file./012'

>>> F.Read ()

'' '

f.readline () reads a line from the file, and the returned string will include a wrap (/ n) ending, if the last line of the file does not have a wrap, the string read in the row is not ending. Removal. Thus, the result returned by readline does not have ambiguity, and when the read result is an empty string, it must be a file tail, read into one '/ n' is blank.

>>> f.readline ()

'This is the first line of the file./012'

>>> f.readline ()

'Second Line of the File / 012'

>>> f.readline ()

'' '

f.ReadLines () repeatedly calls F.Readline (), returns a list of all rows of files.

>>> f.readlines ()

['This is the first line of the file./012', 'second line of the file / 012'] f.write (string) Write the contents of the string to the file and returns NONE.

>>> F.Write ('this is a test / n')

f.Tell () Returns the current read and write of the file object, follow the number of bytes starting from the file. In order to change the read and write position, use "F.Seek (displacement, from where to where). The read and write position Press a reference point plus the displacement to calculate, the reference point is specified with the "from there", start counting from the file head from the file header, takes 1, calculates from the file. The default is 0, starting from the file.

>>> f = Open ('/ tmp / workfile', 'R ')

>>> F.Write ('0123456789abcdef')

>>> F.Seek (5) # From the file header 5 bytes, reach the sixth character

>>> F.Read (1)

'5'

>>> F.seek (-3, 2) # Go to the top 3 characters before the end

>>> F.Read (1)

'd'

The other file is used to call F.Close () to close the file, release the system resources occupied by the file. Use this file object after the file is closed.

>>> f.close ()

>>> F.Read ()

TRACEBACK (InnerMost Last):

FILE "", LINE 1, in?

ValueError: I / O Operation On Closed File

Document objects There are other less common methods, such as isatty () and truncate (), see the library reference manual.

7.2.2 Pickle Module

Strings can easily read from files or write from files. Read the value to trouble, because the read () method always returns a string, to pass the read string to the function such as string.atoi (), convert the string like the '123' to correspond to the corresponding Integer value 123. However, when you want to save more complex data types such as a list, a dictionary or class instance, reading and writing is much more complicated.

Python's design allows programmers to do not have to write to debug-in-calibration code, which provides a standard module called Pickle. This amazing module can convert almost any Python object to a string representation, this process is called pickled, from the object's string represents the recovery object called recovery. Between marinated and antleriage, the object's string representation can be saved in file or data, even through the network connection to the remote computer.

If you have an object x, there is a writable file object f, the simplest pickup object's way is the following line of code:

Pickle.dump (x, f)

In order to restore the object, if the file has been opened, the file object name is still f, then:

x = pickle.load (f)

(There are other usages (marinated and restored, you can pick multiple objects, you can write data to files, see the library reference manual).

Pickle is a standard measures for saving the Python object and is called by other programs or the same program, which is called "lasting object". Because Pickle uses a wide range of Pickle, many of the Python expansion modules pay attention to the newly added data type, such as matrix, can be properly marked and restored.

转载请注明原文地址:https://www.9cbs.com/read-2239.html

New Post(0)