Python tutorial (7): Input and Output

Source: Internet
Author: User
Document directory
  • 7.1.1 format the old string
  • 7.2.1 file object Method
  • 7.2.2 pickle Module

There are several ways to present the output of a program. data can be printed in human readable form or written to a file for future use. This chapter will discuss these possibilities.

7.1 output format

So far, we have encountered two ways to write values, expression statements, and print () functions. (The third method is to use the write () method of the file object. The standard output file can be referenced as SYS. stdout)

Generally, you want to have more control over the output format instead of simply printing it by space. There are two ways to format the output. The first method is that all string processing is done by yourself. You can use string slicing and link operations to create any layout you want. There are some methods for string type to perform useful operations to fill the string to the specified column width. The second method is to use the str. Format () method.

The string module contains a template class that provides another way to replace the value with the string.

Of course, there is another question: how to convert a value to a string. Fortunately, python can convert any value to a string and pass this value to repr () or STR () function.

The purpose of the STR () function is to represent the returned values in the form of human readable. The purpose of the Repr () function is to generate an interpreter-readable representation (or it will force a syntax error if there is no equal syntax ). For objects that do not have a special representation for humans, STR () returns the value of repr. Many values, such as numbers, lists, and dictionary structures, return the same representation for any function. String. In special cases, there are two different representations. Some examples:

There are two ways to write a table with squares and cubes:

Note that in the first example, a space is directly added to each column. in print () mode, spaces are always added between its parameters.

This example demonstrates the str. Just ust () method of the string object, which is used to align the right of the field and fill the space on the left to reach the specified width. Some similar methods are Str. Ljust () and str. Center (). These methods do not write anything. They only return a new string. If the input string is too long and does not truncation the string, return it directly. This will disrupt your column layout, but it is generally better than other methods. In other cases, the value may be truncated. (If you really want to truncation, you can add a slice operator, X. Ljust (n) [: N])

Another method, str. zfill (), is used to add zero to the left of the string. It can understand positive and negative signs:

The basic usage of the str. Format () method is as follows:

Curly braces and characters in them (called format fields) are passed into Str. replace the objects in the format () method. The numbers in braces can be used to reference the input Str. location of objects in the format () method:

If the str. Format () method uses the keyword parameters, you can use the names of these parameters to reference their values:

Location parameters and keyword parameters can be arbitrarily combined:

! A (apply ASCII ())! S (Application STR ())! R (Application repr () can be used to convert values before formatting:

An optional and formatted indicator can be followed by the field name, which allows greater control on how to format the value. The following example shows that PI retains three decimal places:

After: an integer is passed to indicate the character width of the field with the smallest integer. This makes the table beautiful:

If you have a long formatted string and you do not want to separate it, the better way is to reference the formatted variable by name rather than position. This can be simply achieved by passing a dictionary and using square brackets to access the key value:

This can also be achieved using ** the dictionary as a keyword parameter:

This is particularly useful. When combined with the built-in function vars (), it returns a dictionary containing all local variables.

7.1.1 format the old string

The % operator can also be used for string formatting. It explains that the parameter on the left (must be a sprintf () style format string) is applied to the parameter on the right and returns the string result from this formatting operation. For example:

Because Str. Format () is very new, many Python code still uses the % operator. However, the old format will eventually be deleted from the language, and str. Format () should be widely used.

7.2 read/write files

Open () returns a file object, usually using two parameters: open (filename, mode ):

The first parameter is the name of a string containing the file, and the second parameter is the method in which another string contains several characters to describe the file. The method can be R. When a file is read-only, W is only written (an existing file with the same name will be erased), and a is to open the file and append it, any data written into the file is automatically added to the end. R + can read and write files. The mode parameter is optional. If ignored, it is assumed to be r.

Typically, the file is opened in text mode, which means that the string is read and written from the file and encoded by a specified encoding (the default is the UTF-8 ). B. Open the file in binary mode after the append mode. Data Reading and writing are in the form of byte objects. This mode is used for all files that do not contain text.

In text mode, the default value is to convert the platform-specific line ending (UNIX is \ n, Windows is \ r \ n) to \ n, during writing, \ n is converted to the platform-specific line terminator. This behind-the-scenes file data modification is no problem for text files, but will destroy binary data like JPEG or EXE files. Use binary mode with caution when reading and writing such files.

7.2.1 file object Method

The following example assumes that a file object named F has been created.

Read the content of a file and call f. Read (size). It reads a certain amount of data and returns it in the form of a string or Byte object. Size is an optional numeric parameter. When the size is ignored or negative, the content of the entire file is read and returned. If the file size is twice the memory size of your machine, it is your problem. Otherwise, the maximum number of bytes is read and returned. If the end of the file is reached, F. Read () returns an empty string:

F. readline () reads a line from the file. The newline character \ n is left at the end of the string. It is ignored only when the last line of the file ends, provided that the file does not end with a new line. This makes the return value very clear, if F. readline () returns an empty string, indicating that the end of the file has reached. At the same time, a blank line is represented as a \ n string containing only one line break:

F. readlines () returns a list containing all the data rows in the file. If an optional parameter sizehint is given, many bytes are read from the file, enough to complete a row, and these rows are returned. This usually allows effective reading of a large file in the form of rows without loading the entire file into the memory. Only the completed rows are returned:

An optional way to read rows is to loop through a file object. In this way, the memory is effective, fast, and the code is simpler:

This method is relatively simple, but does not provide fine-grained control. Because the two methods manage the cache of rows differently, they cannot be mixed together.

F. Write (string) writes the string content to the file, and returns the number of written characters:

To write something that is not a string, you must first convert it to a string:

F. Tell () returns an integer indicating the position of the object in the file. The value is measured by the number of bytes at the beginning of the file. To change the object location, use F. Seek (offset, from_what ). This position is calculated by adding an offset to a reference point. The reference point is selected using the from_what parameter. 0 indicates starting from the beginning of the file, 1 indicates the current position, and 2 indicates the end of the file as the reference point. It can be ignored. The default value is 0, indicating that the start of the file is used as the reference point:

In a text file (there is no B in the open mode string), only the search relative to the start of the file is allowed (except that seek (0, 2) can be used to find the end of the file ).

When you use up a file, call f. Close () to close it and release any system resources occupied by opening the file. After calling F. Close (), attempts to use the file object will automatically fail:

It is a good practice to use the With keyword when processing file objects. Its advantage is that the file will be properly closed after use, even if an exception occurs during use. It is much shorter than to write equal try-finally blocks:

There are some other methods for file objects, such as isatty () and truncate (), which are used less frequently. Refer to the Reference Library to obtain the complete file object guide.

7.2.2 pickle Module

Strings can be easily written to and read from files. The number takes a little effort, because the read () method returns only strings and will have to be passed to functions like int, it accepts a string like 123 and returns its numeric value 123. However, when you want to save more complex data types such as list, Dictionary, or class instances, things become more complex.

To prevent users from frequently writing and debugging code to save complex data types, Python provides a standard module called pickle. This is an incredible module that can use almost any Python object (or even some Python code form) and convert it into a string representation; this process is called pickling. The string indicates that the re-constructed object is called unpickling. Between pickling and unpickling, the object string indicates that it may have been stored in a file or data, or sent to some remote machines through the network.

If you have an object X, and a file object F has been opened for writing, the simplest way is to pickle the object with only one line of code:

For the unpickle object again, if F is a file object that has been opened for reading:

Pickle is a standard way to store or reuse Python objects by other programs, or be called by the same program in the future. Its technical term is a persistent object. Because pickle is so widely used, many authors who write Python extensions are very careful to ensure that the new data type matrix can be properly pickle and unpickle.

This article is the official website content translation, original address: http://docs.python.org/3/tutorial/inputoutput.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.