Python Guide - Input and Output

zhaozj2021-02-11  283

Chapter directory

7.1 Design Output Format 7.2 Read and write

7.2.1 File Object (File Object) Method 7.2.2 Pickle Module

7. Enter and output

There are several ways to express the output of the program; the data can be printed with readable structures, or it can be written for later use. This chapter will discuss several feasible practices.

7.1 Design Output Format

We have two large-phase migration methods: expression statements and print statements. (The third visit is a wite () method using the file object, the standard file output can be referred to sys.stdout. Details See the library reference manual.)

Maybe you often want to make some more complicated control over the output format than simple print space division. There are two ways to format the output. The first is to control the entire string of the entire string, you can create any output form you want using the character slice and join operation. Standard module String includes some operations that fill the string into the given column, which is useful. Then we will discuss this part. The second method is to use the% operator as its left parameter in a string. The% operator interprets the left parameter as a format string similar to the sprintf () style, and acts on the right parameter, returns a formatted string from this operation.

Of course, there is a problem, how to convert (different) values ​​into strings? Fortunately, Python always passes any value into the REPR () or STR () function, and is converted to a string. Relative to the quotation marks ('') equivalent to REPR (), but does not promote this.

Function STR () is used to convert values ​​to a form suitable for man reading, while REPR () is converted to an interpreter read (if there is no equivalent syntax, the syntaxerror exception will occur) A object is not suitable for people. If you read the explanation, STR () will return to the REPR () equivalent value. Many types, such as values ​​or linked lists, structures such as a dictionary, have a unified interpretation of each function. Strings and floating point numbers have a unique interpretation.

Here are some examples:

>>> s = 'Hello, World.'

>>> STR (s)

'Hello, World.'

>>> REPR (S)

"'Hello, World.'"

>>> Str (0.1)

'0.1'

>>> REPR (0.1)

'0.10000000000000001'

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

>>> # The repr () of a string add string quotes and backslashes:

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

>>> Hellos = Repr (Hello)

>>> Print Hellos

'Hello, World / N'

>>> # The argument to repr () May Be Any Python Object: ... Repr ((x, y, ('spam', 'eggs'))))))))

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

>>> # Reverse Quotes Are Convenient in Interactive Sessions:

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

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

The following two methods can output the square and cube:

>>> Import String

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

... Print String.rjust (Repr (x), 2), String.rjust (REPR (x * x), 3),

... # Note Trailing Comma on Previous Line

... Print String.rjust (REPR (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

(Need to note that there is a space between the two columns when using the Print method: it always adds a space between the parameters.)

The above is a String.rjust () function demonstration, which outputs the string to a column and fill the space to the left side to align it. Similar functions include string.ljust () and String.center (). These functions are only output new strings and do not change anything. If the string of the output is too long, they will not truncate it, but it will output it, which will make your output format confuse, but always over another selection (truncated string), because it will generate errors Output value. (If you really need to truncate it, you can use a slice operation, for example: "String.ljust (x, n) [0: n]".)

There is also a function, string.zfill () it is used to expose the left to the left to fill 0 on the string of the value. This function can correctly understand the corrective number:

>>> Import String

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

'00012'

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

'-003.14'

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

'3.14159265359'

You can use the% operator as follows:

>>> Import Math

>>> Print 'The value of pi is approximately% 5.3f.'% Math.pithe Value of Pi is ApproxImately 3.142.

If there is more than one string to format it, it is necessary to pass them into a tuple as the right value, as shown below:

>>> table = {'sjoerd': 4127, 'Jack': 4098, 'DCAB': 7678}

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

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

...

Jack ==> 4098

DCAB ==> 7678

Sjoerd ==> 4127

Most types of formatting operations require you to get into the appropriate type, but if you don't define an exception, there will be no one from the kernel. (However, if you don't you get an exception, not a core dump) Use the% S format to be more easily: If the corresponding parameter is not a string, it converts the built-in STR () function into a string. Python supports the transmission of width or accuracy with * as an isolated (integer) parameter. Python does not support C's% N and% P operators.

If you can reference the variable name to format by point, you can generate a format string that meets the real length and does not generate intervals. This effect can be implemented by using the form% (Name) structure:

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

>>> PRINT 'JACK:% (JACK) D; Sjoerd:% (SJOERD) D; DCAB:% (DCAB) D'% Table

Jack: 4098; Sjoerd: 4127; DCAB: 8637678

This trick is very useful when used in combination with the new built-in function Vars (), which returns a dictionary containing all local variables.

7.2 read and write files

Open () Returns a file object, usual usage requires two parameters: "Open (filename, Mode)".

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

>>> Print F

The first parameter is a string that identifies the file name. The second parameter is a string consisting of limited letters, which describes how the file will be used. The optional mode is: 'r', this option makes the file read only; 'W', this option makes the file only writes (for the same name file, this action makes the original file overwrites); 'a', this option is appended Way open files; 'R ', this option opens files in reading and writing; if not specified, the default is 'r' mode.

On Windows and Macintosh platforms, 'B' mode opens files in binary, so there may be a combination of 'RB', 'WB', 'R B', etc.. The text file and binary files are different from the two-write files on the Windows platform, and the row will be automatically added. This background operation does not have any problems with the text file, but it is destroyed when it operates JPEG or EXE. When operating these files, you must remember to open in binary mode. (Need to note is the text mode on the MAECTIONTOSH platform depends on the underlying C library it uses. 7.2.1 Method of File Object

The examples in this section are default file object f.

To read the contents of the file, you need to call F.Read (size), which reads several quantities and returns its content as a string, and the string length is specified by the value size. If you do not specify size or a negative number, you will read and return the entire file. An issue will occur when the file size is twice the current machine memory. Under normal circumstances, the data is read and returned as much as possible. If it is at the end of the file, F.Read () will return an empty string ("").

>>> F.Read ()

'This is the entire file./n'

>>> F.Read ()

'' '

F.Readline () reads a single line from the file, the string will automatically add a newline, only when the final row does not have the final line, this operation will be ignored. If the return value will not be confused, if IF f.readline () returns an empty string, then it is said to arrive at the end of the file. If it is an empty line, it will be described as '/ n', one only Contains a string of a wrap.

>>> f.readline ()

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

>>> f.readline ()

'Second Line of the file / n'

>>> f.readline ()

'' '

F.ReadLines () Returns a list that contains all the data lines in the file. If a Sizehint parameter is given, the number of bits of more than one line is read, and the row list is returned. This feature is often used to efficiently read large row files to avoid reading the entire file into memory. This operation only returns a complete line.

>>> f.readlines ()

['This is the first line of the file./n', 'second line of the file / n']

F.Write (string) writes the String content into the file and returns None.

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

f.Tell () Returns an integer that represents the pointer position in the file object in the file, which is measured from the beginning to the number of bits at the pointer. You need to change the file object nuttelling, use "F.seek (offset, from_what)". The pointer moves OFFSET bits from the specified reference position in this operation, and the reference location is specified by the from_what parameter. The from_what value is 0 indicates that the initial starting from the file, 1 indicates that from the current file pointer position, 2 means starting from the end of the file. From_what can be ity, its default value is zero, starting from the file header.

>>> f = open ('/ tmp / workfile', 'R ') >>> F.Write ('0123456789abcdef ")

>>> F.Seek (5) # Go to the 6th byte in the file

>>> F.Read (1)

'5'

>>> F.Seek (-3, 2) # Go to the 3rd byte before the end

>>> F.Read (1)

'd'

After the file is used, call f.close () to turn off the file, release the system resources that open the file. After calling f.close (), call the file object automatically triggers an error.

>>> f.close ()

>>> F.Read ()

TRACEBACK (MOST RECENT CALL LAST):

FILE "", LINE 1, in?

ValueError: I / O Operation On Closed File

File objects There are still some uncommon additional methods, such as isatty () and truncate () in the library reference manual's full guide.

7.2.2 Pickle Module

We can read and write strings in the document. The value must be more than one fold, because the read () method will only return a string, and it should be transferred to the string.atoi () method, and the characters such as '123' can be converted to the corresponding value. However, when you need to save more complex data types, such as linches, dictionaries, classes, things will become more complicated.

Fortunately, users don't have to write and debug code that saves complex data types. Python provides a standard module called Pickle. This is an amazing module that can be used to express any Python objects (even some python code blocks (form)!) As a string, this process is called Pickling. Expressing the restructuring object from a string is called unpickling. Objects in the package can be stored in file or objects, or can be transmitted between remote machines over the network.

If you have an object X, a file object f that is written in a write mode, the simplest method of the package, only one line of code:

Pickle.dump (x, f)

If F is a file object that opens in read mode, you can reload this object:

x = pickle.load (f)

(If you don't want to write the packaged data into the file, there are some other changes available. For complete PICKLE documentation, please see the library reference manual).

Pickle is a standard method that stores the Python object for other programs or itself. Providing this group of techniques is a persistent object ("Persistent Object). Because the use of Pickle is very wide, many Python expansion authors are very note whether the new data types such as matrices are suitable for packaging and unpacking.

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

New Post(0)