Learning python - Common Module

  • random module
  • time module
  • sys module
  • os module
Module takes the random number 
Import Random

# random decimal to: Math
Import Random
 Print (random.random ()) # go between. 1 ~ 0 
Print (random.uniform (1,2)) # within the range to fractional
# To random integer 
# Application: lottery, lottery
Random Import 
Print
(the random.randint (1,2)) # [1,2] Gu Gu tail head is Print (random.randrange (1,2)) # [1,2) care regardless tail Print (random.randrange (1,200,2)) # randomized to the punch 200
# Randomly selected from a list of values 
# Applications: Draw
Import Random 
L = [ ' A ' , ' B ' , (1,2), 123 ]
 Print (The random.choice (L))
 Print (random.sample (L, 2)) # continuously extracted twice, will not be repeated
# Disrupt the order of a list, make changes directly in the original list, saving space 
# application: Shuffle
import random
random.shuffle(l)
print(l)
# Codes 
# 4 integer codes
# 6 bit digital codes
# 6 digits + letter codes

# digital codes
import random
#while 循环
s = ''
while len(s)<4:
    num = str(random.randint(0, 9))
    s = s +num
print(s)
#for循环
s = ''
for i in range(4):
    num = random.randint(0,9)
    s = s + str(num)
print(s)
Digital version of the function code #
import random
def code(n=6):
    s = ''
    while len(s) < n:
        num = str(random.randint(0, 9))
        s = s + num
    return s
print(code(4))
print(code(6))
# Digital Plus letters
import random
def code(n):
    s = ''
    for i in range(n):
        num = random.randint(0,9)
        alpha_upper = chr(random.randint(65,90))
        alpha_lower = chr(random.randint(97,122))
        res = random.choice([num,alpha_upper,alpha_lower])
        s = s +str(res)
    return s
print(code(6))
# Numbers, letters controllable
import random
def code(n,alpha=True):
    s = ''
    for i in range(n):
        num = str(random.randint(0,9))
        if alpha:
            alpha_upper = chr(random.randint(65,90))
            alpha_lower = chr(random.randint(97,122))
            num = random.choice([num,alpha_upper,alpha_lower])
        s = s +num
    return s
print(code(6,True))
 
# Time and time module is mainly used for dealing 
# time format
# '2018-08-20' Data type String Format - posters
# structured time
# 1565748617.8853261 floating-point data type, the time in s time stamp - used to calculate the machine
# 1970110: 0: 0 at this time to London time
the time.sleep (2) # program that will wait 2 go two seconds
# Timestamp time
print(time.time())
# Time Format
Print (The time.strftime ( ' % Y-M-% D%% H:% M:% S ' )) # Format Time 
Print (The time.strftime ( ' % Y-% M-% D% H:% M :% S ' )) # format time 
Print (The time.strftime ( ' % C ' )) # format time
Structured time #
= time.localtime struct_time () # Beijing 
Print (struct_time) # Beijing 
Print (struct_time.tm_year)
# Timestamp - "String Time
print(time.time())
strucy_time = time.localtime(150000000)
ret = time.strftime('%y/%m/%d %H:%M:%S',strucy_time)
print(ret)
# Time String -> timestamp
strucz_time = time.strptime('2018-8-8','%Y-%m-%d')
print(strucz_time)
res = time.mktime(strucz_time)
print(res)
# Look at two billion timestamp date time indicated
strucy_time = time.localtime(2000000000)
ret = time.strftime('%Y/%m/%d %H:%M:%S',strucy_time)
print(ret)
# Convert into a timestamp time 2008-8-8
t = time.strptime('2008-8-8','%Y-%m-%d')
print(t)
print(time.mktime(t))
# Please timestamp time No. 1 of the current month to take out the current time
st = time.localtime()
st2 = time.strptime('%s-%s-1'%(st.tm_year,st.tm_mon),'%Y-%m-%d')
print(time.mktime(st2))
# Calculate the time difference 
# 2018-8-1922: 10: 82018-8-2011: 07: 3
# after a number of minutes and seconds
str_time1 = '2018-8-19 22:10:8'
str_time2 = '2018-8-20 11:07:3'
struct_t1 = time.strptime(str_time1,'%Y-%m-%d %H:%M:%S')
struct_t2 = time.strptime(str_time2,'%Y-%m-%d %H:%M:%S')
timestamp1 = time.mktime(struct_t1)
timestamp2 = time.mktime(struct_t2)
sub_time = timestamp2 - timestamp1
gm_time = time.gmtime(sub_time)
print('过去了%d年%d月%d天%d小时%d分钟%d秒'%(gm_time.tm_year-1970,gm_time.tm_mon-1,
                                       gm_time.tm_mday-1,gm_time.tm_hour,
                                       gm_time.tm_min,gm_time.tm_sec))

 

sys module

 sys module is an interactive interface python interpreter

  sys.argv command line parameters List, the first element is the path to the program itself

  sys.exit (n) to exit the program, when the normal exit exit (0), an error exit sys.exit (1)

  sys.version get Python interpreter version information

  sys.path return path search module, using the value of environment variable initialization PYTHONPATH

  sys.platform return the name of the operating system platform

os module

os.makdirs ( ' dirname1 / dirname2 ' ) may generate a multilayer recursive directory 
os.removedirs ( ' dirname1 ' ) if the directory is empty, delete, and recursively to the parent directory, should be empty, delete, and so analogy 
os.mkdir ( ' dirname ' ) to generate a single level directory; it is equivalent to the shell dirname mkdir 
os.rmdir ( ' dirname ' ) empty directory delete a single stage, if the directory is not empty can not be deleted, being given; corresponds to the shell rmdir dirname 
os.listdir ( ' dirname ' ) lists all the files and subdirectories in the specified directory, including hidden files, and print in a list 
os.remove () to delete a file 
os.rename ( " oldname " , " newname " ) weight name the file / directory 
os.State ( 'path / filename ' ) get the file / directory information 

os.system ( " bash the Command " ) to run shell commands, displayed directly 
os.popen ( " bash the Command) .read () run shell commands to get the results 
os.getcwd () Gets the current working directory that the current directory path python script work 
os.chdir ( " dirname " ) script to change the current working directory; under the equivalent cd shell 


os.path 
os.path.abspath (path) returns the absolute path to the path of standardized 
os. path.split (path) into the path directory and file name tuple returned 
os.path.dirname (path) returns the directory path of the fact that the first element os.path.split (path) of 
os.path. basename (path) returns the last path of the file name. how path to / \ or end, it will return a null value. That os.path.split (path) of the second element 
os.path.exists (path) if the path exist, return True; if the path does not exist, returns False 
os.path.isabs (path) if the path is the absolute path, returns True
os.path.isfile (path) if the path is a file exists, returns True. Otherwise it returns False 
os.path.isdir (path) if the path is a directory exists, then return True. Otherwise it returns False 
os.path.join (path1 [, path2 [, ...]]) will return after a combination of multiple paths parameters before the first absolute path will be ignored 
os.path.getatime (path) return path points to the last access time of a file or directory 
os.path.getmtime (path) returns the file or directory path points to the last modification time 
os.path.getsize (path) return path size

Note: the os.stat ( 'path / filename' obtaining the file / directory information of the structure description  

stat structure: 

The st_mode: the inode protection mode 
st_ino: inode node number. 
st_dev: inode device resides. 
st_nlink: inode number of links. 
st_uid: User ID of the owner. 
st_gid: group ID of the owner. 
st_size: common file unit size in bytes; wait for data containing special file. 
st_atime: Time last accessed. 
st_mtime: last modification time. 
st_ctime: report by the operating system's " ctime " . On some systems (such as Unix) is the time of most recent metadata changes, on the other systems (such as Windows) is the creation time (see platform documentation for more information). 

stat structure
os.sep output operation system-specific path separator for the next win " \\ " , is the Linux " / " 
os.linesep output current platform using line terminator, to win the " \ R & lt \ n- " , under Linux as " \ n- " 
is the character string for dividing a win os.pathsep output file path;, under Linux is: 
the os.name output string indicating the current use internet. win -> ' NT ' ; Linux-> ' POSIX '

Guess you like

Origin www.cnblogs.com/bilx/p/11351489.html