Analysis of input and output examples of Python3 Foundation

Source: Internet
Author: User
Tags value of pi
Typically, a Python program can read input from the keyboard or read input from a file, and the results of the program can be output to the screen or saved to a file for later use. This article describes the most basic I/O functions in Python.

One, console I/O

1. Read keyboard input

The built-in function, input ([prompt]), is used to read a line from the standard input and return a string (minus the end of the newline character):

s = input ("Enter your input:")

Note: the raw_input () function was canceled in Python version 3.x .

2. Print to screen

The simplest way to output this is to use the print statement, which you can pass 0 or more comma-delimited expressions:

The brackets are optional, Sep represents the delimiter, end represents the Terminator, and file represents the redirected files. If you want to assign a value to Sep, end, file, you must use the keyword argument.

Print (' Hello ', ' world ', sep= '% ')  # output Hello%world print (' Hello ', ' world ', end= ' * ')  

II. File I/O

Before reading or writing a file, open a file with the opening () function, which returns a file object:

f = open (Filename,mode)

If you do not specify the mode parameter, the file will be opened by default in ' R ' mode. The characters in the pattern are:

R: Read-only
W: Write only and overwrite if the file already exists. If the file does not exist, create a new file
+: Read and write (cannot be used alone)
A: Open file for Append, write only, do not exist to create new file
B: Open in binary mode (cannot be used alone)

So the possible patterns are R, W, r+, w+, RB, WB, rb+, wb+, A, A +, AB, ab+, and note that only W and a can create files.

Typically, files are opened in text mode, that is, a string that is encoded in a specific encoding format (the default is UTF-8) is read and written from a file. If the file is opened in binary mode, the data will be read and written in the form of a byte object:

f = open (' A.txt ', ' wb+ ') f.write (' I like apple! ')  

The bytes object is a sequence of non-modifiable integers from 0 to 127, or purely ASCII characters, whose purpose is to store binary data.

You can create a bytes literal by adding ' B ' in front of a string;
You can also create a bytes object from the bytes () function.

Note: if the initializer for the bytes () function is a string, you must provide an encoding.

B1 = B ' This is a string ' b2 = bytes (' This is string ', ' UTF-8 ')  

The string object is incompatible with the byte object, and to convert bytes to str, the bytes object must be decoded using the Decode () method:

Method of the file object (assuming F is a file object):

F.read (size): reads a size byte of data and returns it as a string or bytes object. The size is an optional parameter, and if you do not specify a size, all the contents of the file are read.
F.readline (): reads a row. A newline character (\ n) is left at the end of the string, and an empty string is returned if the end of the file.
F.readlines (): reads all rows, stores them in the list, and each element is a row, equivalent to list (f).
F.write (String): Writes a string to a file, returning the number of characters written. If you write a file in binary mode, you need to convert the string to a bytes object.
F.tell (): Returns the current location of the file object, which is the number of bytes that are counted from the beginning of the file.
F.seek (offset, from_what): Changes where the file object is located. Offset is the relative position of the reference, the From_what value 0 (file header, default), 1 (current position), 2 (end of file) represents the reference location.
F.close (): Closes the file object.

These are very common methods, and of course file objects are more than these methods. The type of file object returned by open () differs depending on the mode that is opened:

Textiowrapper: Text mode, returns the Textiowrapper object.
BufferedReader: Read binary, or RB, to return the BufferedReader object.
BufferedWriter: Write and append binary, that is WB, AB, return BufferedWriter object.
Bufferedrandom: Read/write mode, which contains the + mode, returns the Bufferedrandom object.
You can run Dir () or help () on these file objects to see all of their methods.

Add:

1. In text mode, the Seek () method will only be positioned relative to the starting position of the file. (in addition to locating the end of the file can be used to seek (0, 2)
2, you can iterate over a file object one line reads:

Third, formatted output

In general, we want more control over the output format, rather than simply dividing it into spaces. There are two ways of doing this:

The first is your own control. Use string slices, join operations, and some useful operations that string contains.
The second is the use of the Str.format () method.
An example is given below:

# The first way: Self control for x in range (1, one):   print (str (x). Rjust (2), str (x*x). Rjust (3), end= ")   print (str (x*x*x). Rjust (4 )  # Second way: Str.format () for x in range (1, one):   print (' {0:2d} {1:3d} {2:4d} '. Format (x, X*x, x*x*x))  # output is: # 1  1  1 # 2  4  8 # 3  9  27 # 4 16  

In the first way, the Str.rjust () method of the String object is the function of the string to the right, and by default fills the space on the left, and similar methods have Str.ljust () and Str.center (). These methods do not write anything, they simply return a new string, and if the input is long, they do not truncate the string. We note that the same output of a square with a cubic table, using Str.format () will be much easier.

The basic usage of Str.format () is as follows:

The parentheses and the characters in parentheses will be replaced by the parameters in format (). The numbers in parentheses are used to specify the location of the incoming object:

If keyword parameters are used in format (), their values point to parameters that use that name:

The optional ': ' and format identifiers can be followed by field name, which allows for better formatting:

Passing in an integer after ': ' Guarantees that the field has at least so many widths and is useful for beautifying tables:

>>> table = {' Jack ': 4127, ' Rose ': 4098, ' Peter ': 7678} >>> for name, phone in Table.items ():   ... Print (' {0:10} ==> {1:10d} '. Format (name, phone)  ... Peter   ==>    7678 Rose    ==>    4098 Jack    ==>    

We can also format the output of the parameter unpacking. For example, unpack the table as a keyword parameter:

Add:

The% operator can also implement string formatting. It takes the left argument as a formatted string similar to the sprintf () format, and the right generation:

Import Math Print (' The value of pi is%10.3f. '%math.pi) # output: The value of pi is   

Because this legacy formatting will eventually be removed from the Python language, more str.format () should be used.

Attached: text mode and binary mode

1, in the Windows system, in text mode, the default is the Windows platform's end-of-line identifier \ r \ n When read, and write to \ r \ n. This hidden behavior is not a problem for text files, but it can be problematic for binary data like JPEG or EXE. Use binary mode carefully when using these files.

2, in the class Unix/linux system, the end of the line identifier is \ n, that is, the file is \ n for line break. Therefore, there is no difference between the text mode and the binary mode in the Unix/linux system.

The example reader described in this article can be tested in practical hands to deepen the impression and thus gain a solid grasp of the Python Foundation.

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