[Python 3 learning notes - basic grammar] how does the input and output function realize dynamic interaction with the computer

Keywords: Python Pycharm

In the previous chapters, we have actually touched on the input and output functions of Python. In this chapter, we will introduce the input and output of Python in detail.

If you are interested in learning Python together, click the following icon to add a group:

Output format beautification

Python has two ways to output values: expression statements and print() functions.

The third way is to use the write() method of the file object. The standard output file can be referenced with sys.stdout.

If you want the output to be more diverse, you can use the str.format() function to format the output value.

If you want to convert the output value into a string, you can use the repr() or str() function.

  • str(): the function returns a user-friendly expression.
  • repr(): produces an interpreter readable expression.

for example

>>> s = 'Hello, Python Chicken with vegetables'
>>> str(s)
'Hello, Python Chicken with vegetables'
>>> repr(s)
"'Hello, Python Chicken with vegetables'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'x The value of is: ' + repr(x) + ',  y The value of is:' + repr(y) + '...'
>>> print(s)
x The value of is: 32.5,  y The value of is 40000...
>>> #  The repr() function can escape special characters in a string
... hello = 'hello, Python Chicken with vegetables\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, Python Chicken with vegetables\n'
>>> # The argument to repr() can be any Python object
... repr((x, y, ('Google', 'Python Chicken with vegetables')))
"(32.5, 40000, ('Google', 'Python Chicken with vegetables'))"

There are two ways to output a square and cubic table:

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # Note the use of the previous line 'end'
...     print(repr(x*x*x).rjust(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('{0:2d} {1:3d} {2:4d}'.format(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

**Note: * * in the first example, the spaces between each column are added by print().

This example shows the rjust() method of a string object, which can keep the string to the right and fill in spaces on the left.

There are similar methods, such as ljust() and center(). These methods don't write anything, they just return a new string.

Another method, zfill(), fills 0 to the left of the number, as follows:

>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'

The basic use of str.format() is as follows:

>>> print('{}:  "{}!"'.format('Python Chicken with vegetables', 'Python Study notes'))
Python Chicken with vegetables: "Python Study notes"

The parentheses and the characters inside them (called formatting fields) will be replaced by the parameters in format().

The number in parentheses is used to point to the position of the incoming object in format(), as shown below:

>>> print('{0} and {1}'.format('Google', 'Python Chicken with vegetables'))
Google and Python Chicken with vegetables
>>> print('{1} and {0}'.format('Google', 'Python Chicken with vegetables'))
Python Chicken with vegetables Google

If keyword parameters are used in format(), their values point to the parameter with that name.

>>> print('{name}website: {site}'.format(name='Python Study notes', site='www.Python Chicken with vegetables.com'))
Python Learning Notes website: www.Python Chicken with vegetables.com

Location and keyword parameters can be combined arbitrarily:

>>> print('Site list {0}, {1}, and {other}. '.format('Google', 'Python Chicken with vegetables', other='Taobao'))
Site list Google, Python Chicken with vegetables, and Taobao. 

! A (using ASCII ())! S (using str()) and! r (using repr()) can be used to convert a value before formatting it:

>>> import math
>>> print('constant PI The approximate value of is: {}. '.format(math.pi))
constant PI The approximate value of is: 3.141592653589793. 
>>> print('constant PI The approximate value of is: {!r}. '.format(math.pi))
constant PI The approximate value of is: 3.141592653589793. 

Optional: and format identifiers can be followed by field names. This allows better formatting of values. The following example retains Pi to three decimal places:

>>> import math
>>> print('constant PI The value of is approximately {0:.3f}. '.format(math.pi))
constant PI The value of is approximately 3.142. 

Pass in an integer after: to ensure that the field has at least so much width. Useful for beautifying tables.

>>> table = {'Google': 1, 'Python Chicken with vegetables': 2, 'Taobao': 3}
>>> for name, number in table.items():
...     print('{0:10} ==> {1:10d}'.format(name, number))
...
Google     ==>          1
Python Chicken with vegetables   ==>          2
Taobao     ==>          3

If you have a long format string and you don't want to separate them, it's good to format by variable name instead of position.

The simplest is to pass in a dictionary and use square brackets [] to access key values:

>>> table = {'Google': 1, 'Python Chicken with vegetables': 2, 'Taobao': 3}
>>> print('Python Chicken with vegetables: {0[Nowcoder]:d}; Google: {0[Google]:d}; Taobao: {0[Taobao]:d}'.format(table))
Python Chicken with vegetables: 2; Google: 1; Taobao: 3

You can also use * * in front of the table variable to achieve the same function:

>>> table = {'Google': 1, 'Python Chicken with vegetables': 2, 'Taobao': 3}
>>> print('Python Chicken with vegetables: {Python Chicken with vegetables:d}; Google: {Google:d}; Taobao: {Taobao:d}'.format(**table))
Python Chicken with vegetables: 2; Google: 1; Taobao: 3

Legacy string formatting

%Operators can also implement string formatting. It takes the parameters on the left as a format string similar to sprintf(), substitutes the parameters on the right, and then returns the formatted string. For example:

>>> import math
>>> print('constant PI The approximate value of is:%5.3f. ' % math.pi)
constant PI The approximate value of is: 3.142. 

Because str. Format () is a relatively new function, most Python code still uses the% operator. But because this old-fashioned formatting will eventually be removed from the language, you should use str.format()

Read keyboard input

Python provides the input() built-in function to read a line of text from standard input. The default standard input is the keyboard.

Input can receive a Python expression as input and return the operation result.

#!/usr/bin/python3

str = input("Please enter:");
print ("What did you enter: ", str)

This will produce the following results corresponding to the input:

Please enter: Python Study notes
 What did you enter:  Python Study notes

Read and write files

open() will return a file object. The basic syntax format is as follows:

open(filename, mode)
  • filename: a string value containing the name of the file you want to access.
  • Mode: determines the mode of opening the file: read-only, write, append, etc. All desirable values are shown in the complete list below. This parameter is optional. The default file access mode is read-only ®.

Full list of files opened in different modes:

patterndescribe
rOpen the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
rbOpen a file in binary format for read-only. The file pointer will be placed at the beginning of the file.
r+Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
rb+Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.
wOpen a file for writing only. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wbOpen a file in binary format for writing only. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
w+Open a file for reading and writing. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wb+Open a file in binary format for reading and writing. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
aOpen a file for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
abOpen a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
a+Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file is opened in append mode. If the file does not exist, create a new file for reading and writing.
ab+Open a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.

The following figure summarizes these modes:

patternrr+ww+aa+
read++++
write+++++
establish++++
cover++
Pointer at start++++
Pointer at end++

The following example writes a string to the file foo.txt:

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "w")

f.write( "Python Is a very good language.\n Yes, it's really very good!!\n" )

# Close open files
f.close()
  • The first parameter is the file name to open.
  • The second parameter describes the characters used in the file. Mode can be 'r', if the file is read-only, 'w' is only used for writing (if there is a file with the same name, it will be deleted), and 'a' is used to append the file content; Any data written will be automatically added to the end. 'r +' is also used for reading and writing. The mode parameter is optional‘ r 'will be the default.

The file foo.txt opens as follows:

$ cat /tmp/foo.txt 
Python Is a very good language.
Yes, it's really very good!!

Method of file object

The remaining examples in this section assume that a file object called f has been created.

f.read()

To read the contents of a file, call f.read(size), which reads a certain amount of data and returns it as a string or byte object.

Size is an optional numeric parameter. When size is ignored or negative, all the contents of the file will be read and returned.

The following example assumes that the file foo.txt already exists (created in the above example):

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "r")

str = f.read()
print(str)

# Close open files
f.close()

Execute the above procedure, and the output result is:

Python Is a very good language.
Yes, it's really very good!!

f.readline()

f.readline() reads a single line from the file. The newline character is' \ n '. f. If readline() returns an empty string, it indicates that the last line has been read.

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "r")

str = f.readline()
print(str)

# Close open files
f.close()

Execute the above procedure, and the output result is:

Python Is a very good language.

f.readlines()

f.readlines() will return all the lines contained in the file.

If the optional parameter sizehint is set, bytes of the specified length are read and divided into rows.

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "r")

str = f.readlines()
print(str)

# Close open files
f.close()

Execute the above procedure, and the output result is:

['Python Is a very good language.\n', 'Yes, it's really very good!!\n']

Another way is to iterate over a file object and read each line:

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "r")

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

# Close open files
f.close()

Execute the above procedure, and the output result is:

Python Is a very good language.
Yes, it's really very good!!

This method is simple, but it does not provide a good control. Because the processing mechanisms of the two are different, it is best not to mix them.

f.write()

f.write(string) writes a string to a file and returns the number of characters written.

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "w")

num = f.write( "Python Is a very good language.\n Yes, it's really very good!!\n" )
print(num)
# Close open files
f.close()

Execute the above procedure, and the output result is:

29

If you want to write something that is not a string, you will need to convert it first:

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo1.txt", "w")

value = ('www.Python Chicken with vegetables.com', 14)
s = str(value)
f.write(s)

# Close open files
f.close()

Execute the above procedure and open the foo1.txt file:

$ cat /tmp/foo1.txt 
('www.Python Chicken with vegetables.com', 14)

f.tell()

f.tell() returns the current location of the file object, which is the number of bytes from the beginning of the file.

f.seek()

If you want to change the current location of the file, you can use the f.seek(offset, from_what) function.

from_ The value of what. If it is 0, it means the beginning. If it is 1, it means the current location. If it is 2, it means the end of the file. For example:

  • seek(x,0): move x characters from the starting position, that is, the first character of the first line of the file
  • seek(x,1): indicates to move x characters backward from the current position
  • seek(-x,2): move x characters forward from the end of the file

from_ The default value of what is 0, which is the beginning of the file. A complete example is given below:

$ cat /tmp/foo1.txt 
('www.Python Chicken with vegetables.com', 14)

f.close()

In text files (those that do not b exist in the open file mode), they are located only relative to the starting position of the file.

When you finish processing a file, call f.close() to close the file and release the resources of the system. If you try to call the file again, you will throw an exception.

>>> f.close()
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file

When dealing with a file object, using the with keyword is a very good way. At the end, it will help you close the file correctly. It is also shorter than the try - finally statement block:

>>> with open('/tmp/foo.txt', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

There are other methods for file objects, such as isatty() and truss (), but these are usually less used.

pickle module

The pickle module of python implements the basic data sequence and deserialization.

Through the serialization operation of pickle module, we can save the object information running in the program to a file for permanent storage.

Through the deserialization operation of the pickle module, we can create the last program saved object from the file.

Basic interface:

pickle.dump(obj, file, [,protocol])

With the pickle object, you can open the file in the form of reading:

x = pickle.load(file)

**Note: * * read a string from file and reconstruct it into the original python object.

File: class file object with read() and readline() interfaces.

Example 1

#!/usr/bin/python3
import pickle

# Use the pickle module to save data objects to a file
data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}

selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)

output = open('data.pkl', 'wb')

# Pickle dictionary using protocol 0.
pickle.dump(data1, output)

# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)

output.close()

Example 2

#!/usr/bin/python3
import pprint, pickle

#Using the pickle module to reconstruct python objects from files
pkl_file = open('data.pkl', 'rb')

data1 = pickle.load(pkl_file)
pprint.pprint(data1)

data2 = pickle.load(pkl_file)
pprint.pprint(data2)

pkl_file.close()

If you are interested in learning Python together, click the following icon to add a group:

Posted by yumico23 on Thu, 14 Oct 2021 20:28:25 -0700