python built-in module continuation

[toc]

python built-in module sequel

Continue with the previous python built-in module and continue to write the following module

  • Random module: random number
  • os module: operating system related module
  • sys module: a module commonly used by python interpreter
  • json module: special module for data interaction
  • subprocess module: a module often used for remote operations

1. random random number module

The method of random module is as follows:

  • random.random (): randomly generate a decimal between 0 and 1
  • Random. Random (a, b): randomly generate an integer between a and B
  • random.uniform(a,b): randomly generate a decimal between a and B
  • random.choice(seq): randomly extract an element from the sequence with equal probability
  • random.sample(population, k, count): randomly select a specified number of samples
  • random.shuffle(list): randomly shuffle many elements in the container

Method usage example:

1. random() method

import random
# Randomly generate a random number between 0 and 1
num = random.random()
print(num)
# >>>0.9158120687169333

2. randint(a,b) method

import random
# Randomly generate a range of random numbers
num = random.randint(0,10)
print(num)
# >>>3

3. uniform(a,b) method

import random
# Randomly generate a range of decimals
num = random.uniform(0,5)
print(num)
# >>>2.3192301761260783

4. choice (seq) method

import random
# Randomly select an element: lottery example
num = random.choice(['Grand Prize','the first prize','second award','third award','Participation Award','Thank you for your patronage'])
print(num)
# >>>Grand Prize

5. sample(population, k, count) method

import random
# Quantitative samples shall be randomly selected, and two samples shall be selected at one time
num = random.sample(['Hebei Province','Henan Province','Shandong Province','Shanxi Province','Beijing','Shanghai'],2)
print(num)
# >>>['Shanxi Province', 'Beijing city']

6. shuffle(list) method

import random
# Disrupt the elements in the container, shuffle example
lst_card = [2,3,4,5,6,7,8,9,10,'A','J','Q','k',]
random.shuffle(lst_card) # Shuffle the order
print(lst_card)
# >>>[3, 'Q', 9, 4, 7, 2, 'A', 6, 'J', 10, 5, 8, 'k']

7. random module comprehensive exercise

'''
Sogou company written test questions
 The random verification code can be any combination of numbers, lowercase letters and uppercase and lowercase letters
 Write a random verification code that can generate five digits
ps:Each of the five can be one of three situations
'''
# Verify the randomness of the code, using random
import random


for i in range(5):
    code_num = random.randint(0, 9)  # Get random numbers from 0 to 9
    code_lower = chr(random.randint(97, 122))  # Get the characters of a-z and convert numbers to ASCII
    code_upper = chr(random.randint(65, 90))  # Get the characters of A-Z and convert numbers to ASCII
    # Grab any one randomly
    get_code = random.choice([code_num,code_lower,code_upper])
    print(get_code,end='')

Upgrade version

import random

# Define a function that can obtain a verification code of any length
def get_anylen_code(n):
    code = ''
    for i in range(n):
        code_num = str(random.randint(0, 9))  # Get random numbers from 0 to 9
        code_lower = chr(random.randint(97, 122))  # Get the characters of a-z and convert numbers to ASCII
        code_upper = chr(random.randint(65, 90))  # Get the characters of A-Z and convert numbers to ASCII
        # Grab any one randomly
        get_code = random.choice([code_num,code_lower,code_upper])
        # print(get_code,end='')
        code+=get_code
    return code

# Get 10 digit verification code
print(get_anylen_code(10))  # >>>0AP9xSUmFY
# Get 6-digit verification code
print(get_anylen_code(6)) # >>>2q6de0
# Get 4-digit verification code
print(get_anylen_code(4)) # >>>k3Y1

2. os module

This module often deals with the operating system. The matching method of os module is as follows:

  • os.mkdir (folder): create a single level directory
  • os.makedirs (multi-level folder): create multi-level directories
  • os.rmdir (folder): delete empty directory
  • Os.removediers (multi-level folder): delete multi-level empty directories
  • OS. Path. Dirname (_ file): get the path where the current file is located (if it can be nested, it is the path of the upper layer)
  • Os.path.join (path 1, path 2): used for path splicing
  • Os.listdir (path): lists the file names under the specified path
  • OS. Remove (file name): deletes a file
  • os.rename(oldname,newname): modify the file name
  • os.getcwd(): get the current working path
  • Os.chdir (path): switch paths
  • Os.path.exists (file name): judge whether the current path exists
  • Os.path.isfile (file): judge whether the current path is a file
  • Os.path.isdir (folder): judge whether the current path is a folder
  • Os.path.getsize (file name): get the file content size, and output the following bytes

Method usage example:

1. MKDIR (folder) method

Create a single tier directory

import os
# Create a single tier directory
os.mkdir(r'HammerZe')
# Error in creating multi-layer directory
os.mkdir(r'HammerZe\Ze')

2. makedirs method

Create multi tier directory

import os

# Create multi tier directory
os.makedirs(r'HammerZe\Ze')

3. rmdir (folder) method

This method can only delete single level empty directories

import os

# Delete single level directory
os.rmdir(r'E:\Old_BoyClass_fourth\Ze')
'''Ze I created the file in advance'''

4. Removediers (multi-level folders)

Although this method can write multi-layer paths, it can only delete empty directories

import os

# Delete single level directory
os.removedirs(r'E:\Old_BoyClass_fourth\HammerZe')

5. Os.path.dirname (_ file _) method

Get the current file path, which can be nested to return to the previous path

import os
# Get the path where the current file is located
print(os.path.dirname(__file__)) 
# >>>E:/Old_BoyClass_fourth
# Nested use to obtain the path of the previous layer
print(os.path.dirname(os.path.dirname(__file__)))
# >>>E:/

6. Os.path.join (path 1, path 2)

Path splicing

import os
# Path splicing
# Get current file path
now_dir = os.path.dirname(__file__)
print(now_dir) #E:/Old_BoyClass_fourth/join
# Path splicing, find the test.py file
join_dir = os.path.join(now_dir,'test.py')
print(join_dir)
# E:/Old_BoyClass_fourth/join\test.py

7. Listdir (path)

Lists the file names in the specified directory. The file names are returned in the form of a list

import os
# Displays the file name under the specified path
find_dir = os.listdir(r'E:\Old_BoyClass_fourth\Mv')
print(find_dir)

'''a,b,c I built the file myself'''
# ['a.txt', 'b.txt', 'c.txt']
import os
# Advanced exercise: get the files in the specified directory and select the file to enter

# Get current file path
now_dir = os.path.dirname(__file__) # >>> E:/Old_BoyClass_fourth
# Splice the first layer
one_join = os.path.join(now_dir,r'E:\Old_BoyClass_fourth\Mv') # >>E:\Old_BoyClass_fourth\Mv
# Gets the files in the specified directory
dir_list= os.listdir(r'E:\Old_BoyClass_fourth\Mv')  # ['a.txt', 'b.txt', 'c.txt']
# By enumerating, the file name is determined by the index value
for index,values in enumerate(dir_list,1):
    print(index,values)
# Get the serial number of the file you want to view
select_num = input('please input your select number>>>:').strip()
if select_num.isdigit():
    select_num = int(select_num)
    # The index to get a file cannot exceed the number of files
    if select_num in range(len(dir_list)+1):
        # Index to get the corresponding file name
        file_name = dir_list[select_num-1]
        # Splice file paths to obtain the exact location of a, B and C files
        dir_join = os.path.join(one_join,file_name)
        # read file
        with open(dir_join,'r',encoding='utf8') as read_f:
            print(read_f.read())

8. Remove (file name)

Delete a file

import os
os.remove(r'E:\Old_BoyClass_fourth\Mv\drop.py')

9,rename(oldname,newname)

Modify file name

import os
os.rename('Mv','findtxt')

10,getcwd()

Get current working path

import os
# Get current working path
print(os.getcwd()) # E:\Old_BoyClass_fourth

11. Chdir (path)

Switch path

import os
# Get current working path
print(os.getcwd()) # E:\Old_BoyClass_fourth
os.chdir('D:')
print(os.getcwd()) # D:\

12. Os.path.exists (file name)

Judge whether the current path exists

import os
# Output True if present
print(os.path.exists(r'E:\Old_BoyClass_fourth\findtxt\a.txt'))
print(os.path.exists(r'E:\Old_BoyClass_fourth\findtxt\b.txt'))
# True 
# True

# Output False if it does not exist
print(os.path.exists(r'E:\Old_BoyClass_fourth\findtxt\z.txt'))
# >>>False

13. Os.path.isfile (file)

Determine whether it is a file

import os

# E:\Old_BoyClass_fourth\findtxt\a.txt'
print(os.path.isfile(r'E:\Old_BoyClass_fourth\findtxt\a.txt'))
print(os.path.isfile(r'E:\Old_BoyClass_fourth\findtxt'))
# True
# False

14. Os.path.isdir (folder)

Determine whether it is a folder

import os

# E:\Old_BoyClass_fourth\findtxt\a.txt'
print(os.path.isdir(r'E:\Old_BoyClass_fourth\findtxt\a.txt'))
print(os.path.isdir(r'E:\Old_BoyClass_fourth\findtxt'))
# False
# True

15. Os.path.getsize (file name)

Gets the size of the file content and outputs it in bytes

import os

print(os.path.getsize(r'E:\Old_BoyClass_fourth\findtxt\a.txt'))
# A text content: a file
# Result > > > 7, a is one byte and the file is six bytes

3. sys module

  • sys.path: get the string set of the specified module search path. You can put the written module under a path, which can be found correctly during import in the program, or you can add the module path (emphasis)
    • Sys.path.append (path)
  • sys.version: get version number
  • sys.platfotm: get the current system platform
  • sys.argv: get the absolute path of the current executable file (focus)

1,sys.path,sys.version,sys.platfotm

import sys

print(sys.path)
print(sys.version)
# 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)]
print(sys.platform)
# win32

sys.path is described in the customization module~

2,sys.argv[ ]

arg does not follow [] and returns the absolute path of the file

import sys
print(sys.argv) # >>>['E:/Old_BoyClass_fourth/test.py']

arg and [] get parameters from outside to return a list. Open cmd and run py file to demonstrate:

import sys
print(sys.argv) # >>>['E:/Old_BoyClass_fourth/test.py']

index_v = sys.argv[1]
print(index_v)

Add an argv[2]:

import sys
print(sys.argv) # >>>['E:/Old_BoyClass_fourth/test.py']

index_v = sys.argv[1]
index_v2 = sys.argv[2]
print(index_v,index_v2)

Dynamic presentation:

import sys
index_v = sys.argv[1]
index_v2 = sys.argv[2:]
print(index_v,index_v2)

4. json module

How can barrier free transmission be achieved in different programming languages? Who is the "translator" in the middle? For example, the list in python becomes an array in js. At this time, json module can be the "translator". The main function of json module is to transmit across languages

  • The identification of json string is double quotation marks. Strings with double quotation marks are json strings
  • Process:
    • Serialization: dumps() method
    • Deserialization: loads() method
  • jsom module only supports partial data type serialization, as follows:
Supports the following objects and types by default:
+-------------------+---------------+
| Python            | JSON          |
+===================+===============+
| dict              | object        |
+-------------------+---------------+
| list, tuple       | array         |
+-------------------+---------------+
| str               | string        |
+-------------------+---------------+
| int, float        | number        |
+-------------------+---------------+
| True              | true          |
+-------------------+---------------+
| False             | false         |
+-------------------+---------------+
| None              | null          |
+-------------------+---------------+
import json

dic = {'username': 'HammerZe', 'pwd': 123}
str_json = json.dumps(dic)
print(str_json)
# Serialization result: {username ":" hammerze "," PWD ": 123}

dic_json = json.loads(str_json)
print(dic_json)
# Deserialization: {username ':'hammerze','pwd ': 123}

# file store
with open(r'E:\Old_BoyClass_fourth\findtxt\a.txt','w',encoding='utf8') as w_f:
    str_json = json.dumps(dic)
    w_f.write(str_json)

with open(r'E:\Old_BoyClass_fourth\findtxt\a.txt','r',encoding='utf8') as r_f:
    res = r_f.read()
    print(json.loads(res))
    
# result
{"username": "HammerZe", "pwd": 123}
{'username': 'HammerZe', 'pwd': 123}
{'username': 'HammerZe', 'pwd': 123}

  • Dump (serialized object, file)
  • Load (serialized object, file)

These two methods are short for dumps and loads, which can serialize the dictionary into a file and deserialize it out

import json

dic = {'username': 'HammerZe', 'pwd': 123}
# file store
with open(r'E:\Old_BoyClass_fourth\findtxt\a.txt','w',encoding='utf8') as w_f:
    seq_str = json.dump(dic,w_f)

with open(r'E:\Old_BoyClass_fourth\findtxt\a.txt','r',encoding='utf8') as r_f:
    nonseq_str = json.load(r_f)
    print(nonseq_str)
    
# result
# {'username': 'HammerZe', 'pwd': 123}

5. subprocess module

This module can connect to a computer based on the network, let the connected computer execute the commands we need to execute, and finally return the command results

  • cmd to view the currently running commands

  • Use the command to ask the win terminal in pycharm
import subprocess
# Processes running in the current system
res = subprocess.Popen('tasklist',
                       shell=True,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE
                       )
print('stdout',res.stdout.read().decode('gbk'))  # Get the results after the correct command is executed
print('stderr',res.stderr.read().decode('gbk'))
'''windows Computer internal code defaults to GBK'''

Tags: Python

Posted on Fri, 26 Nov 2021 20:19:28 -0500 by diode