python Foundation (19):random module, time module, sys module, os module

1. random module

The imported random module is in the following format:

import random

1.1 random decimal

Take random decimal: mathematical calculation.

print(random.random()) ා take the decimal between 0-1 (random. Uniform (1,2)) ා take the decimal between 1-2

1.2 random integer

Take random integer: used in lottery and lottery.

print(random.randint(1,2)) # [1,2]print(random.randrange(1,2)) # [1,2)print(random.randrange(1,200,2)) # [1,2)

1.3 randomly extract values from the list

Draw values at random from a list, such as a lottery.

l = ['a','b',(1,2),123]

1.4 disorder list order

To disrupt the order of a list and modify it directly on the basis of the original list to save space, such as shuffling.


2. time module

Time module is mainly used to deal with time

The time module is imported in the following format:

import time

Time format:

'2018-8-20' '2018.8.20' string data type format time - for people to see
 Structured time
 1534732642.617272 floating point data type, time stamp time in s - for machine calculation
1970 1 1 0:0:0

2.1 time stamp time


2.2 format time

print(time.strftime('%Y-%m-%d %H:%M:%S')) # str format timeprint(time.strftime('%y-%m-%d %H:%M:%S')) # str format timeprint(time.strftime('%c'))

2.3 structured time

struct_time = time.localtime()  # Beijing timeprint(struct_time)print(struct_time.tm_mon)

2.4 time stamp to string time

struct_time = time.localtime(1500000000)# print(time.gmtime(1500000000))ret = time.strftime('%y-%m-%d %H:%M:%S',struct_time)print(ret)

2.5 string time to time stamp

struct_time = time.strptime('2018-8-8','%Y-%m-%d')
print(struct_time)res = time.mktime(struct_time)print(res)

3. sys module

sys works with Python interpreters

The sys module is imported in the following format:

import sys

3.1 argv

print(sys.argv)  # argv The first parameter of is python The value after this commandusr = input('username')pwd = input('password')usr = sys.argv[1]pwd = sys.argv[2]if usr == 'xhh' and pwd == 'xhh0308':  print('Login successfully')else:  exit()

3.2 path

Is the module in the interpreter? No.
The module should be on the hard disk,
But when I use it, I import the module.

Whether a module can be imported smoothly depends on whether there is a module under sys.path.
When customizing a module, you need to pay more attention to sys.path when importing a module.

3.3 modules

print(sys.modules)  # Is the name of all the modules we import into memory : Memory address of this moduleprint(sys.modules['re'].findall('\d','abc126'))

4. os module

The os module is imported in the following format:

import os

os is a module that interacts with the operating system

4.1 common methods of OS module

os.makedirs('dirname1/dirname2')    Can generate multi-level recursive directory
os.removedirs('dirname1')    If the directory is empty, delete it, and recurse to the previous directory; if it is also empty, delete it, and so on
os.mkdir('dirname')    Generate a single level directory; equivalent to shell in mkdir dirname
os.rmdir('dirname')    Delete single level empty directory. If the directory is not empty, it cannot be deleted and an error is reported shell in rmdir dirname
os.listdir('dirname')    Lists all files and subdirectories under the specified directory, including hidden files, and prints them in list mode
os.remove()  Delete a file
os.rename("oldname","newname")  rename file/Catalog
os.stat('path/filename')  get files/catalog information

os.system("bash command")  Function shell Command, direct display
os.popen("bash command).read()  Function shell Command, get execution result
os.getcwd() Get the current working directory, i.e. current python Directory path for script work
os.chdir("dirname")  Changes the current script working directory; equivalent to shell lower cd

os.path.abspath(path) Return path The absolute path of standardization
os.path.split(path) take path Split into directory and filename 
os.path.dirname(path) Return path Directory. In fact, that is os.path.split(path)First element of 
os.path.basename(path) Return path Last filename. How path with/or\At the end, a null value is returned. Namely os.path.split(path)Second element of
os.path.exists(path)  If path Exist, return True;If path No, return False
os.path.isabs(path)  If path Is the absolute path, return True
os.path.isfile(path)  If path Is an existing file, return True. Otherwise return False
os.path.isdir(path)  If path Is an existing directory, return True. Otherwise return False
os.path.join(path1[, path2[, ...]])  If multiple paths are combined and returned, the parameters before the first absolute path will be ignored
os.path.getatime(path)  Return path Last access time of the file or directory pointed to
os.path.getmtime(path)  Return path Last modification time of the file or directory pointed to
os.path.getsize(path) Return path Size

4.2 stat structure

Note: structure description of os.stat('path/filename ') to obtain file / directory information

stat structure:

st_mode: inode protection mode
 St Ou ino: inode node number.
St_dev: the device where the inode resides.
St_nlink: number of links for inode.
St UUID: the user ID of the owner.
st_gid: group ID of the owner.
st_size: the size of a normal file in bytes; contains data waiting for some special files.
st_atime: time of last visit.
st_mtime: the time of the last modification.
st_ctime: the "CTime" reported by the operating system. On some systems (such as Unix) is the time of the latest metadata change, and on other systems (such as Windows) is the time of creation (see the platform's documentation for details).

4.3 properties of OS module

os.sep outputs the path separator specific to the operating system, which is "\ \" under win and "/" under Linux
 os.linesep outputs the line terminator used by the current platform, which is "\ R \ n" under win and "\ n" under Linux
 The output string of os.pathsep used to split the file path is under win; and under Linux is:
The output string indicates the platform currently in use. win->'nt'; Linux->'posix'

Tags: Python shell Linux Unix

Posted on Fri, 08 Nov 2019 08:48:09 -0500 by marco839