Analysis of input and output examples of Python3 Foundation _python

Source: Internet
Author: User

Typically, a Python program can read input from the keyboard or read input from a file, and the results of the program can be printed 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. Reading keyboard input

built-in function input ([prompt]), which reads a row from the standard input and returns a string that removes the end line feed:

s = input ("Enter your input:")

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

2. Print to screen

The simplest way to do this is with the print statement, which you can pass 0 or more expressions separated by commas:

print ([Object, ...] [, Sep= '] [, end= ' Endline_character_here '] [, File=redirect_to_here]) 

Within square brackets is optional, Sep represents the separator, end is the Terminator, and file represents the redirected file. If you want to specify values for Sep, end, and file, you must use keyword parameters.

Print (' Hello ', ' world ', sep= '% ')  # output Hello%world 
print (' Hello ', ' world ', end= ' * ')  # output Hello world*, and does not wrap. 

Second, file I/O

Before you read and write to a file, open a file with the open () function, which returns a file object:

f = open (Filename,mode)

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

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

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

Typically, a file is opened in text mode, that is, a string that is encoded in a specific encoding format (the default is UTF-8), read and write from a file. If the file is opened in binary mode (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! ')  # error 
F.write (b ' I like apple! ') # Read and write in bytes object form 

The bytes object is an immutable sequence of integers from 0 to 127, or a pure ASCII character, and its purpose is to store binary data.

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

Note: If the initialization of the bytes () function is a string, you must provide an encoding.

B1 = B ' This are string ' 
b2 = bytes (' Is String ', ' UTF-8 ')  # must specify encoding format 

String objects are incompatible with byte objects, and to convert bytes to str, the bytes object must be decoded, using the Decode () method:

b = Bytes (' This is string ', ' UTF-8 ') 
print (b, B.decode (), sep= ' \ n ') 
# output: 
# B ' This is String ' 
# this is St Ring 

The method of the file object (assuming F is a file object):

F.read (size): reads the size byte of data and returns as a string or bytes object. Size is an optional parameter, and if size is not specified, all contents of the file are read.
F.readline (): reads a row. A newline character (\ n) is left at the end of the string, or an empty string if the end of the file is returned.
F.readlines (): reads all rows, is stored in the list, 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 string to a bytes object.
F.tell (): Returns the current position of the file object, which is the number of bytes from the beginning of the file.
F.seek (offset, from_what): Changes the location of the file object. Offset is the from_what of the relative reference position, with the value 0 (file header, default), 1 (current position), 2 (end of file) representing the reference position.
F.close (): Closes the file object.

These are commonly used methods, and of course file objects are more than just these methods. Open () returns a different file object type depending on the mode that is being opened:

Textiowrapper: Text mode, returning Textiowrapper object.
BufferedReader: Read binary, or RB, to return the BufferedReader object.
BufferedWriter: Write and append binary, namely 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 locates only relative to the starting position of the file. (You can use Seek (0, 2) In addition to the end of the location file)
2. You can iterate over one line of a file object to read:

For line in F: 
print (line, end= ') 

Third, the format of the output

In general, we want more control over the output format than simply separating it with a space. There are two ways of doing this:

The first is in your own control. Use string slices, join operations, and some useful actions that string contains.
The second is the use of the Str.format () method.
Here's an example:

# The first way: 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)) 
 
# The second way: Str.format () 
for x in range (1, one): 
  print (' {0:2d} {1:3d} {2:4d} '. Format (x, X*x, x*x*x)) c7/># output are: 
# 1  1  1 
# 2  4 8 # 3 9 
# 4 
# 5 25 125 
# 6 216 
# 7 343 
# 8 # 
9 Bayi 729 
# 10 100 1000 

In the first way, the Str.rjust () method of the string object is to keep the string to the right and by default fill the space on the left, and similar methods include 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 is the output of a square and cubic table, the use of Str.format () will be very convenient.

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

>>> print (' We are the ' {} say ' {}! '. Format (' Knights ', ' Ni ')] 
We are the Knights who say "ni!" 

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

>>> print (' {0} and {1} '. Format (' Kobe ', ' James ')) 
Kobe and James 
>>> print (' {1} and {0} '). Format (' Kobe ', ' James ')) 
James and Kobe 

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

>>> print (' The {thing} is {adj}. ') Format (thing= ' flower ', adj= ' Beautiful ')) The 
flower is beautiful. 

The option ': ' and the format identifier can follow field name, which allows for better formatting:

>>> Import Math 
>>> print (' The value of PI is {0:.3f}. ') Format (MATH.PI)) The 
value of pi is 3.142. 

Passing in an integer after ': ' Ensures 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    ==>    4127 

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

Table = {' Jack ': 4127, ' Rose ': 4098, ' Peter ': 7678} 
Print (' Jack is {Jack}, Rose's ' {Rose} ', Peter is {Peter}. ') Format (**table)) 
# output: Jack is 4127, Rose are 4098, Peter is 7678. 

Add:

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

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

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 to change the end of the Windows platform identifier, \ r \ n, to \ n when it is read, and to \ r \ n when writing. This hidden behavior is not problematic 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 to represent the newline. So there is no difference between the text mode and the binary mode in the Unix/linux system.

The example reader in this article can actually do hands-on testing to deepen the impression and thus further firmly grasp the Python foundation.

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.