Day22 application module

Contents:
a time and datetime module
two random module
three os module
four sys module
five shutil module
six json & pickle module

Time Module
# Module time priority to master the operation of
# a: Time
Import Time

Time is divided into three formats #:
# 1, the time stamp: from 1970 to present seconds elapsed
# effect: for calculating the time interval

# print(time.time())

# 2, according to a certain format of time: 2020-03-30 11:11:11
# effect: a presentation time

# print(time.strftime('%Y-%m-%d %H:%M:%S %p'))
# print(time.strftime('%Y-%m-%d %X'))

# 3, the structure of the time
# effect: a portion for acquiring time alone

# res=time.localtime()
# print(res)
# print(res.tm_year)
# print(res.tm_yday)

#二:datetime
import datetime

# Can directly display time format
# print (datetime.datetime.now ())

# May be plus or minus the number of minutes, days, weeks, second and other operations, such as n 3 is the calculated time after three days, a few days operation performed
# print (datetime.datetime.now () + datetime.timedelta (days = 3 ))
# Print (datetime.datetime.now () + the datetime.timedelta (= weeks. 1))

 

# Operation time need to have the module
# 1, the time format conversion
# struct_time-> # stamp is converted into a structured time stamp
Import Time
# S_TIME time.localtime = ()
# Print (time.mktime (S_TIME))

# Timestamp -> struct_time converted into a structured time stamp
# tp_time the time.time = ()
# Print (time.localtime (tp_time))

# Added: Coordinated Universal Time and local time
# print (time.localtime ()) # Shanghai China time, China in the East eight districts
# print (time.gmtime ()) # Universal Time, Greenwich Observatory, UK time, understand
# Print (time.localtime (333333333))
# Print (time.gmtime (333333333))


Structured Time # struct_time -> formatted string time
# S_TIME time.localtime = ()
# Print (The time.strftime ( '% Y-M-% D%% H:% M:% S', s_time))

The format of this string of time "1988-03-03 11:11:11" converted into a structured time struct_time
# print (time.strptime ( '1988-03-03 11:11:11 ', '% Y-% m-% d% H: % M:% S '))


# !!! really need to know only one (two formats conversion time): format string formatted string of time <------> timestamp timestamp

# '1988-03-0311: 11: 11' + 7
# assume this is a vip user recharge time '1988-03-03 11:11:11', the users recharge seven days vip, needs to the obtained seven days after the time
# format string at this time need to first be converted into a structured time period, and then reconverted to the time stamp
do this requires two addition operations, the first step is converted to the time stamp formatting characters then do the addition operation to do, and then back to the time after addition of the format string

Step one:
# format String ---> struct_time ---> timestamp

Struct_time the time.strptime = # ( '1988-03-03 11:11:11', '% Y-M-% D%% H:% M:% S')
# time.mktime (struct_time) This step is to give All of seconds, and then one day is 86,400 seconds at 7 days by
# = time.mktime timestamp (struct_time) +. 7 * 86400
# Print (timestamp) which obtained in step # seconds after the addition of all

Step two:
# format String <--- struct_time <--- timestamp

# res=time.strftime('%Y-%m-%d %X',time.localtime(timestamp))
# print(res)

time of sleep function:
# the time.sleep (3)


Knowledge of #
# Import Time
# Print (time.asctime ())


datetime Import
# Print (datetime.datetime.now ()) # linux in common, to obtain a similar time format The time.strftime
# Print (datetime.datetime.utcnow ()) # standard time mean

# Timestamp format is converted into a string of time
print (datetime.datetime.fromtimestamp (333333))

 

random module, takes random values
import random

# Print (random.random ()) # (0,1) ---- float decimal between greater than 0 and less than the 1
# Print (the random.randint (1,. 3)) # [l, 3] is greater than or equal to 1 and less than or equal to an integer between 3

# Print (random.randrange (1, 3 )) # [1,3) is greater than 1 and less than or equal to an integer between. 3
#
# Print (The random.choice ([111, 'AAA', [. 4,. 5]]) ) # randomly from a predetermined type of, or 1 or 23 [4,5]
#
# Print (random.sample ([111, 'AAA', 'CCC', 'ddd'], 2)) # can be specified for each times the number of values taken out, where the list element is specified combination of any two
#
# Print (random.uniform (1, 3)) is greater than the fractional # 1 is less than 3, such as 1.927109612082716
#
# Item = [1, 3, . 5,. 7,. 9]
# random.shuffle (item) # scramble the item, corresponding to "shuffle"
# Print (item)

# Application: random verification code

Import Random #
#
# RES = ''
# for I in Range (. 6):
# remove a randomly = chr (random.randint (65,90)) from the 26 capital letters
# chr will refer to this table to uppercase ascii letters, ascii table 65-90 is the corresponding uppercase AZ
# remove a randomly = str (random.randint (0,9)) 10 numbers from
#
# random characters = random.choice ([26 capital letters from remove a random, random remove a]) from 10 numbers
# res + = random characters

Implementation code:
Import Random

def make_code(size=4):
res=''
for i in range(size):
s1=chr(random.randint(65,90))
s2=str(random.randint(0,9))
res+=random.choice([s1,s2])
return res

print(make_code(6))

os module:

The os.getcwd () Gets the current working directory, i.e., the current working directory path python script
os.chdir ( "dirname") a script to change the current working directory; corresponding to the CD the shell
os.curdir Returns the current directory: ( '.')
OS .pardir Get parent directory of the current directory name string :( '..')
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 on
os.mkdir ( 'dirname') to generate a single level directory; is equivalent to the shell dirname mkdir
os.rmdir ( 'dirname') remove empty single-stage directory, if the directory is not empty can not be deleted, an error; the equivalent of a shell dirname rmdir
os.listdir ( 'dirname') lists all the files and subdirectories in the specified directory, including hidden files, and print as a list
os.remove () delete a file
os.rename ( "oldname", "newname ") rename the file / directory
os.stat ( 'path / filename') get the file / directory information
os.sep output operation system-specific path separator, win under the "\\", to "/" under Linux
os.linesep output current platform Line terminator as "\ r \ n" under win,

os.name output string indicating the current use internet. win -> 'NT'; Linux -> 'the POSIX'
os.system ( "bash the Command") to run shell commands, direct display
os.environ acquisition system environment variables
os.path.abspath (path) Returns the path normalized absolute path
os .path.split (path) to the directory path and file name into tuple returned
os.path.dirname (path) returns the path of the directory. In fact, os.path.split (path) of the first element
os.path.basename (path) Returns the last path of the file name. How path to / \ or end, it will return a null value. I.e. The os.path.split (path) of the second element
os.path.exists (path) path, if present, returns True; if the path does not exist, returns False
os.path.isabs (path) if the path is an 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 the file or directory
os.path.
os.path.getsize (path) returns the size of path


import os

# Obtain a certain folder and all subfolders and name the subfolder
# os.listdir RES = ( '.')
# Print (RES)
#
# This function is os.path.getsize folder size statistics, the unit is the number of bytes
# size = os.path.getsize (r '/ Users / linhaifeng / PycharmProjects / s14 / day22 / 01 time module .py')
# Print (size)


# Os.remove () to delete a file
# os.rename ( "oldname", " newname") to rename the file / directory


# Applications ---- "" LS / "
# os.system (" LS / ")

# Provision: key and value must be a string

# Os.environ [ 'aaaaaaaaaa'] = '111'
# print (os.environ)


# print(os.path.dirname(r'/a/b/c/d.txt'))
# print(os.path.basename(r'/a/b/c/d.txt'))


# print(os.path.isfile(r'笔记.txt'))
# print(os.path.isfile(r'aaa'))
# print(os.path.isdir(r'aaa'))

# print(os.path.join('a','/','b','c','d'))

 


# Recommended this
base_dir = os.path.dirname (os.path.dirname (__ file__))
# Print (base_dir)


# BASE_DIR=os.path.normpath(os.path.join(
# __file__,
# '..',
# '..'
# ))
# print(BASE_DIR)

# After python3.5, we launched a new module pathlib
from pathlib Import Path

# res = Path(__file__).parent.parent
# print(res)


# res=Path('/a/b/c') / 'd/e.txt'
# print(res)

# print(res.resolve())

sys module

1 sys.argv List command line arguments, the first element of the program itself path
2 sys.exit (n) to exit the program, when the normal exit Exit (0)
. 3 The sys.version Python interpreter acquires version information
4 sys.maxint maximum Int value of
5 sys.path return module search path, use the PYTHONPATH environment variable initialization value
6 sys.platform return to the operating system platform name

import sys

2. 3. 1 python3.8 run.py #
# acquired after the sys.argv interpreter parameter
# print (sys.argv)

# src_file=input('源文件路径: ').strip()
# dst_file=input('目标文件路径: ').strip()
#
# src_file=sys.argv[1]
# dst_file=sys.argv[2]
# # 判断
#
# with open(r'%s' %src_file,mode='rb') as read_f,\
# open(r'%s' %dst_file,mode='wb') as write_f:
# for line in read_f:
# write_f.write(line)

# python3.8 run.py src_file dst_file


# print('[%-50s]' %'#')
# print('[%-50s]' %'##')
# print('[%-50s]' %'###')

 

# import time
#
# res=''
# for i in range(50):
# res+='#'
# time.sleep(0.5)
# print('\r[%-50s]' % res,end='')


import time


def progress(percent):
if percent > 1:
percent = 1
res = int(50 * percent) * '#'
print('\r[%-50s] %d%%' % (res, int(100 * percent)), end='')

recv_size=0
total_size=1025011

recv_size the while <total_size:
the time.sleep (0.01) # 1024 bytes downloaded data

recv_size+=1024 # recv_size=2048

# Print progress bar
# Print (recv_size)
Percent = recv_size / total_size # 1024/333333
Progress (Percent)


Personal Test: Print progress bar

# Print progress bar

# Print ( '[% - 50s ]'% '#') This is the format string, -50 - is left-aligned
# end = '' is not meant wrap
# \ r is the beginning of the line to every print

# 初级版:
# import time
# res=''
# for i in range(50):
# res+='#'
# time.sleep(0.5)
# print('\r[%-50s]' % res,end='')

# Upgrade: increased according to the number of percentage control the #
import time

def progress(percent):

if percent > 1:
percent = 1
res = int(50 * percent) * '#'

print('\r[%-50s] %d%%' % (res, int(100 * percent)), end='')

recv_size = This is the amount of data received # 0
total_size = 333333 # total amount of data to download

recv_size the while <total_size:
the time.sleep (0.01) # 0.3 seconds after assuming 1024 bytes have been downloaded data
recv_size + = 1024

# Print progress bar
Percent = recv_size / total_size # 1024/333333
Progress (Percent)


shutil module (understanding of knowledge)
Advanced files, folders, compressed packet processing module
shutil.copyfileobj (fsrc, fdst [, length ])
will copy the contents of the file to another file
. 1 Import shutil
2
. 3 shutil.copyfileobj (Open ( 'old.xml', 'R & lt'), Open ( 'new.xml', 'W'))

shutil.copyfile (the src, DST)
copy files
1 shutil.copyfile ( 'f1.log', ' f2.log ') # destination file need not exist

shutil.copymode (src, dst)
only copy rights. Content, groups, users remain unchanged
1 shutil.copymode ( 'f1.log', ' f2.log') # file must exist

shutil.copystat (src, dst)
only copy status information, comprising: mode bits, atime , the mtime, the flags
. 1 shutil.copystat ( 'F1.log', 'f2.log') # file must exist

shutil.copy (src, dst)
copies of files and permissions
. 1 Import the shutil
2
. 3 shutil.copy ( 'F1. log ',' f2.log '



Import the shutil. 1
2
. 3 shutil.copy2 ( 'F1.log', 'f2.log')

shutil.ignore_patterns (* Patterns)
shutil.copytree (the src, DST, symlinks = False, the ignore = None)
recursively copied to the folder
Import the shutil. 1
2
. 3 shutil.copytree ( 'Folder1', 'folder2', the ignore shutil.ignore_patterns = ( '*. the pyc', '* tmp')) # destination directory does not exist, attention must folder2 directory parent directory write permission, ignore mean exclusion


import shutil

shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))

'' '
Generally regarded copy to soft copy hard link connection, that treats soft connections, create a new file
' ''


shutil.rmtree (path [, ignore_errors [, onerror]])
recursively to delete the file
. 1 Import the shutil
2
. 3 shutil.rmtree ( 'Folder1')

shutil.move (the src, DST)
recursively to move a file, similar to a command mv , in fact, renamed.
Import the shutil. 1
2
. 3 shutil.move ( 'Folder1', 'the folder3')

shutil.make_archive (base_name, the format, ...)
to create compressed files and return path, for example: zip, tar
create archive file and return path, For example: ZIP, tar
base_name: archive file name, it can be compressed path. Just when the file name is saved to the current directory, or saved to a specified location,
such as data_bak => Save to the current path
, such as: / tmp / data_bak => Save to / tmp /
format: compressed packet type, "zip", "tar "," bztar "," gztar "
ROOT_DIR: to compress folder path (current default directory)
owner: the user, the default current user
group: group, default current set
logger: for logging, the object is usually logging.Logger

# 1 in the file / data packaging program current directory is placed
2 Import the shutil
. 3 shutil.make_archive RET = ( "data_bak", 'gztar', ROOT_DIR = '/ data')
. 4
. 5
. 6 # under the file / data are placed packaged / tmp / directory
. 7 Import the shutil
. 8 shutil.make_archive RET = ( "/ tmp / data_bak", 'gztar', ROOT_DIR = '/ Data')

 

Guess you like

Origin www.cnblogs.com/python--wang/p/12601582.html