Python3 based input and output case analysis

  • 2020-04-02 13:54:37
  • OfStack

In general, a Python program can read input from a keyboard or from a file. The results of the program can be output to the screen or saved to a file for later use. This article introduces the most basic I/O functions in Python.

Console I/O

1. Read keyboard input

Built-in input([prompt]) to read a line from standard input and return a string (minus the line break at the end) :


s = input("Enter your input:")

Note: the raw_input() function has been removed from the Python 3.x version.

Print to the screen

The simplest output method is the print statement, to which you can pass zero or more comma-separated expressions:


print([object, ...][, sep=' '][, end='endline_character_here'][, file=redirect_to_here]) 

The brackets are optional, sep represents the separator, end represents the terminator, and file represents the redirection file. To specify values for sep, end, file, you must use keyword arguments.


print('hello', 'world', sep='%')  #  The output  hello%world 
print('hello', 'world', end='*')  #  The output  hello world* And no line breaks  

Ii. Document I/O

Before reading or writing 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 parameter, the file opens in 'r' mode by default. The characters in the pattern are:

R: read only
W: just write, overwrite the file if it already exists. If the file does not exist, create a new file
+ : read and write (cannot be used alone)
A: open the file for appending, just write, and create a new file if it doesn't exist
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+, noting that only w and a can create files.

Typically, files are opened in text mode, meaning that strings encoded in a particular encoding format (the default is utf-8) are read and written from the file. If the file is opened in binary mode, the data is read and written as a byte object:


f = open('a.txt','wb+') 
f.write('I like apple!')  #  An error  
f.write(b'I like apple!') #  In order to bytes The form of the object is read and written  

The Bytes object is an unmodifiable sequence of integers from 0 to 127, or pure ASCII characters, used to store binary data.

You can create a bytes literal by prefixing a string with 'b';
You can also create a bytes object through the bytes() function.

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


b1 = b'This is string' 
b2 = bytes('This is string', 'UTF-8')  #  The encoding format must be specified  

To convert bytes to STR, the bytes object must be decoded. Use the decode() method:


b = bytes('This is string', 'UTF-8') 
print(b, b.decode(), sep='n') 
#  Output:  
# b'This is string' 
# This is string 

Method of file object (assuming f is a file object) :

F.ead (size) : reads data in bytes and returns it as a string or bytes object. Size is an optional parameter; if you do not specify size, all the contents of the file are read.
F.radline () : reads a row. A newline character (\n) is left at the end of the string, and an empty string is returned if you go to the end of the file.
F.readlines () : reads all rows, stores them in a list, and each element is a row, equivalent to list(f).
F.rite (string) : writes a string to a file and returns the number of characters written. If you write in binary mode, you need to convert the string to the bytes object.
F.ttell () : 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 position of the file object. Offset is the offset relative to the reference position, and the values of from_what 0 (file header, default), 1 (current position), and 2 (file tail) represent the reference position.
F.lose () : closes the file object.

These are all very common methods, but there's more to file objects than that. Open () returns a different type of file object depending on the open mode:

TextIOWrapper: text mode that returns a TextIOWrapper object.
BufferedReader: read binary, rb, returns the BufferedReader object.
BufferedWriter: writes and appends binaries, namely wb and ab, returning the BufferedWriter object.
BufferedRandom: the read/write mode, that is, the mode with +, returns the BufferedRandom object.
You can run dir() or help() on these file objects to see all their methods.

Supplement:

1. In text mode, the seek() method locates only relative to the start of the file. (except that the end of the file can be located by seek(0, 2))
2. A file object can be read line by line by loop iteration:


for line in f: 
print(line, end='') 

Format the output

In general, we want to have more control over the output format, rather than simply whitespace. Here are two ways:

The first is under your control. Use string slices, concatenation operations, and some useful operations that string contains.
The second is to use the STR. Format () method.
Here's an example:


#  The first way: control yourself  
for x in range(1, 11): 
  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, 11): 
  print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) 
 
#  The output is:  
# 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 

In the first case, the str.rjust() method of the string object holds the string to the right and fills the space on the left by default, similar to str.ljust() and str.center(). These methods don't write anything, they just return a new string, and they don't truncate the string if the input is long. We notice that the same square and cubic tables are output, so using STR. Format () is much more convenient.

The basic usage of STR. Format () is as follows:


>>> print('We are the {} who say "{}!"'.format('knights', 'Ni')) 
We are the knights who say "Ni!" 

The e brackets and the characters in them will be replaced by the parameters in format(). The number in parentheses is used to specify the position 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 keyword parameters are used in format(), their values point to the parameters using that name:


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

The optional ':' and format identifier can be followed by the field name 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 that much width, which is useful for beautifying a table:


>>> 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 table as keyword parameter:


table = {'Jack':4127, 'Rose':4098, 'Peter':7678} 
print('Jack is {Jack}, Rose is {Rose}, Peter is {Peter}.'.format(**table)) 
#  Output: Jack is 4127, Rose is 4098, Peter is 7678. 

Supplement:

The % operator also implements string formatting. It takes the parameters on the left as a sprintf-like format string and replaces the ones on the right:


import math 
print('The value of PI is %10.3f.' %math.pi) 
#  Output: The value of PI is   3.142. 

Because this old-style formatting will eventually be removed from the Python language, STR. Format () should be used more often.

Attachment: text mode and binary mode

1. In Windows, the default is to change the line end identifier \r\n to \n when reading and \n to \r\n when writing in text mode. This hiding behavior is fine for text files, but can be problematic for binary data like JPEG or EXE. Be careful to use binary mode when using these files.

2. In unix-like /Linux systems, the end-of-line identifier is \n, that is, the file represents the newline with \n. So there is no difference between text mode and binary mode on Unix/Linux systems.

The examples described in this article will give you a hands-on test to impress you and give you a solid foundation in Python.


Related articles: