Python full stack development "Tenth" Python Common Module II (time, random, OS, SYS, and serialization)

Source: Internet
Author: User
Tags format definition month name python script

One, Time module

Three ways to represent time:

Timestamp: Number (the computer can recognize)

Time string: t= ' 2012-12-12 '

Structured time: Time.struct_time (tm_year=2017, tm_mon=8, Tm_mday=8, Tm_hour=8, tm_min=4, tm_sec=32, Tm_wday=1, tm_yday=220, tm_ Isdst=0) Like this is structured time

 #time模块的常用方法及三种时间之间的转换import time# Object: Object. Method #---------------------------- ------# 1. Timestamp (number): Read Print to Computer (Time.time ()) #当前时间的时间戳print (Time.localtime ()) #结构化时间对象s =time.localtime () # Current structured Time object (UTC time) print (s.tm_year) s2=time.gmtime () #这个和localtime只是小时不一样print (S2) #------------------------------- ----# 2. Conversion of Time print (Time.localtime (15648461)) #把时间戳转换成结构化时间t = ' 2012-12-12 ' #这是一个字符串时间print (Time.mktime ( Time.localtime ())) #将结构化时间转换成时间戳print (Time.strftime ("%y-%m-%d", Time.localtime ())) #将结构化时间转换成字符串时间print ( Time.strftime ('%y/%m/%d%h:%m:%s ')) #小写的y是取得年的后两位print (Time.strptime (' 2008-03-12 ', "%y-%m-%d")) #将字符串时间转换成结构化时间 
#python中时间日期格式化符号:%y Two-digit year (00-99)%y Four-digit year represents (000-9999)%m month (01-12) Day (0-31)%H 24-hour hours (0-23)%I 12-hour hours (01-12)%M minutes (00=59)%s seconds (00-59)%a Local simplified week name%a Local full week name%b Local simplified month name%b Local full month name%c local corresponding date representation and time representation%j One day of the year (001-366)%p local a.m. or p.m. the number of weeks in the year (00-53) Sunday for the beginning of the week%w Weeks (0-6), Sunday for the beginning of the week%w the week of the Year (00-53) Monday for the beginning of the week%x Local corresponding date indicates%x local corresponding time represents%z current time zone name%% number itself

Time.strftime (' format definition ', ' structured time ') if the structured time parameter is not passed, the current time is displayed

Print (Time.strptime (' 2008-03-12 ', "%y-%m-%d")) Print (Time.strftime ('%y-%m-%d ')) Print (Time.strftime ("%y-%m-%d", Time.localtime (15444)))

Asctime and CTime methods

Print (Time.asctime (Time.localtime (150000))) print (Time.asctime (Time.localtime ())) # Time.ctime (timestamp) If the parameter is not passed, the formatted string of the current time is returned directly to print (Time.ctime ()) Print (Time.ctime (150000))

Second, random module

# The method of random import random#----------------------------# 1. Random Fractional print (Random.random ()) #大于0且小于1之间的随机小数print ( Random.uniform (1,3))  #大于1且小于3的随机小数 #----------------------------# 2. Random integer print (random.randint (1,5)) # Integer print (Random.randrange (1,10,2)) that is greater than 1 and less than or equal to 5  #大于等于1且小于3之间的整数 (and is all odd) #----------------------------# 3. Randomly select a return print (Random.choice ([1, ' [4,5]]) #) #----------------------------# 4. Randomly select to return multiple print (Random.sample ([1, ' 23 ', [4,5]],2])  #列表元素任意两个组合 #----------------------------#----------------------------# 5. Scramble List Order item=[1,5,2,3,4 ]random.shuffle (item)  #打乱次序print (item)
# code Small Example (this just produces random four digits) # method One, # l=[]# for I in range (4): # L.append (str (random.randint (0,9)) # print ('. Join (L)) # Print ( L) # Method two # print (Random.randint (1000,9999) # Verification code upgrade # requirements: First to have numbers, followed by letters, altogether four bits, can repeat # chr (65-90) #a-z# chr (97-122) #A-Z Method One # Num_list = List (range) # new_num_l=list (Map (str,num_list)) #[' 0 ', ' 1 ' ... ' 9 ']# l=[] #用来存字母 # for I in Range (65,91): # Zi FU=CHR (i) # l.append (Zifu) #[' A '-' Z ']# new_num_l.extend (l) #要把上面的数字和下面的字母拼在一块 # Print (new_num_l) # ret_l=[] #存生成的随机数字或字母 # for I in range (4): #从new_num_l里面选数字选择四次就放到了ret_l里面) # ret_l.append (Random.choice (new_num_l)) # # print (ret_l) # print (' '. Join (ret_l)) #拼成字符串方法二 # import random# def myrandom (): # new_num_l=list (Map (Str,range)) # L=[CHR (i) for I in R Ange (65,91)]# new_num_l.extend (L) # Ret_l=[random.choice (new_num_l) for I in range (4)]# return '. Join (ret_l) # Print (Myrandom ()) method three import randoml=list (str)) +[CHR (i) for I in range (65,91)]+[CHR (j) for J in Range (97,122)] Print (". Join (Random.sample (l,4)))

Third, OS module

Common methods of OS modules

OS.GETCWD () Gets the current working directory, that is, the directory path of the current Python script work os.chdir ("DirName") changes the current script working directory, equivalent to the shell Cdos.curdir return the current directory: ('. ') Os.pardir Gets the parent directory string name of the current directory: (' ... ') Os.makedirs (' dirname1/dirname2 ') can generate a multi-level recursive directory Os.removedirs (' dirname1 ') if the directory is empty, then deleted, and recursively to the previous level of the directory, if also empty, then delete, and so on Os.mkdir (' DirName ') to generate a single-level directory, equivalent to the shell mkdir dirnameos.rmdir (' dirname ') delete the single-level empty directory, if the directory is not empty can not be deleted, error; equivalent to the shell rmdir Dirnameos.listdir (' dirname ') lists all files and subdirectories under the specified directory, including hidden files, and prints os.remove () Delete a file Os.rename ("Oldname", "newname") Rename File/directory Os.stat (' Path/filename ') Get File/directory information OS.SEP output operating system-specific path delimiter, win under "\ \", Linux for "/" OS.LINESEP output the current platform using the line terminator, win under "\t\n", Linux "\ N "os.pathsep output is used to split the file path of the string win under;, Linux: The Os.name output string indicates the current use of the platform. Win-> ' NT ';  Linux-> ' POSIX ' Os.system ("Bash command") runs a shell command that directly displays Os.popen ("Bash command") to run the shell command to get execution results Os.environ Get system environment variable Os.pathos.path.abspath (PATH) returns path normalized absolute path Os.path.split (path) splits path into directory and file name two tuples return Os.path.dirname (path) Returns the directory of path. In fact, the first element of Os.path.split (path) os.path.basename returns the last file name of path. How PAth ends with a/or \, then a null value is returned. The second element of Os.path.split (path), os.path.exists (path), returns True if path exists, or if path does not exist, returns Falseos.path.isabs if path is an absolute path, Returns Trueos.path.isfile (path) If path is an existing file and returns True. Otherwise, return Falseos.path.isdir (path) True if path is a directory that exists.  Otherwise return Falseos.path.join (path1[, path2[, ...])  When multiple paths are combined, the parameters before the first absolute path are ignored Os.path.getatime (path) returns the last access time of the file or directory to which path is pointing os.path.getmtime (path) Returns the size of the file or directory to which path was last modified Os.path.getsize (path) returned path

Note: Os.stat (' path\filename ') Gets the structure description of the file \ directory information

Stat structure: St_mode:inode Protected Mode st_ino:inode node number. The device that the St_dev:inode resides on. St_nlink:inode number of links. St_uid: The owner's user ID. St_gid: The group ID of the owner. St_size: The size of the normal file in bytes, including data waiting for certain special files. St_atime: Time of last visit. St_mtime: The time of the last modification. St_ctime: "CTime" reported by the operating system. On some systems (such as UNIX), the time of the most recent metadata change,<br> on other systems (such as Windows) is the creation time (see the documentation for the platform for more information).

Four, sys module

SYS module is an interface that interacts with the Python interpreter

# SYS module Import sysprint (SYS.ARGV) #实现从程序外部向程序传递参数. (in command line output open path execution) name=sys.argv[1] #命令行参数List, the first element is the path of the program itself password = sys.argv[2]if name== ' egon ' and password = = ' 123 ':    print (' Continue program ') Else:   exit () Sys.exit () #退出程序, exit Normal exit (0) print (sys.version) #获取python解释的版本信息print ( Sys.maxsize) #最大能表示的数, the number of bits associated with the system print (Sys.path) #返回模块的搜索路径, initialized with the value of the PYTHONPATH environment variable print (sys.platform) #返回操作系统平台名称

  

V. Serialization module

1. What is serialization-------the process of converting an original dictionary, list, and so on into a string is called serialization.

2. Purpose of serialization

1. Persisting a custom object in some form of storage

2. Passing objects from one place to another

3. Make the program more maintainable

Json

The JSON module provides four functions: dumps, loads, dump, load

# dumps and Loadsimport jsondic={' K1 ': ' v1 ', ' K2 ': ' v2 ', ' K3 ': ' V3 '}print (Type (dic ) Str_dic = Json.dumps (DIC) #将字典转换成字符串, the elements in the converted dictionary are print (Str_dic,type (str_dic)) #{"K1" in double quotation marks: "v1", "K2": "V2", "K3": " V3 "} <class ' str ' >dic2 = json.loads (str_dic) #将一个字符串转换成字典类型print (Dic2,type (dic2)) #{' K1 ': ' v1 ', ' K2 ': ' v2 ', ' K3 ': ' V3 '} <class ' dict ' >list_dic = [1,[' A ', ' B ', ' C '],3,{' K1 ': ' v1 ', ' K2 ': ' v2 '}]str_dic = Json.dumps (list_dic) #  You can also handle nested data types print (type (str_dic), str_dic) #<class ' str ' > [1, ["A", "B", "C"], 3, {"K1": "V1", "K2": "v2"}]list_dic2 = Json.loads (str_dic) print (Type (LIST_DIC2), list_dic2) #<class ' list ' > [1, [' A ', ' B ', ' C '], 3, {' K1 ': ' v1 ', ' K2 ': ' v2 ' }]
# Dump and Loadimport jsonf=open (' Json_file ', ' w ') dic = {' K1 ': ' v1 ', ' K2 ': ' v2 ', ' K3 ': ' V3 '}json.dump (dic,f) # #dump方法接收一个文件句柄 , convert the dictionary directly to a JSON string to write to the file F.close () F = open (' json_file ') Dic2 = Json.load (f)  #load方法接收一个文件句柄, Converts a JSON string in a file directly into a data structure return F.close () print (Type (DIC2), Dic2)

 

Pickle

JSON and Pickle modules

JSON: Used to convert between string and Python data types

Pickle: Conversion for Python-specific types and Python data types

# pickle Dumps,sump and Loads,load method #--------------------------Import pickle# dic= {' K1 ': ' v1 ', ' K2 ': ' v2 ', ' K3 ': ' V3 '}# str _dic=pickle.dumps (DIC) # print (str_dic)  #打印的是bytes类型的二进制内容 # # Dic2 = Pickle.loads (str_dic) # print (DIC2)  # Yes, the dictionary is converted back. Import timestruct_time  = Time.localtime (1000000000) print (struct_time) f = open (' Pickle_file ', ' WB ') Pickle.dump (struct_time,f) f.close () F = open (' Pickle_file ', ' RB ') struct_time2 = Pickle.load (f) Print (struct_time.tm_ Year

Shelve

Shelve is also a serialization tool provided to us by Python, which is simpler to use than pickle.
Shelve only provides us with an open method, which is accessed using key and is similar to a dictionary.

# shelve Module Import SHELVEF = Shelve.open (' shelve_file ') f[' key ' = {' int ': Ten, ' float ': 9.5, ' string ': ' Sample Data '}  # Directly to the file handle operation, you can deposit data f.close () Import shelvef1 = Shelve.open (' shelve_file ') existing = f1[' key ']  # When you take out the data, you just need to get it directly with the key, but if key doesn't exist, it will F1.close () print (existing)

There is a limit to this module, which does not allow multiple applications to write to the same db at the same time. So when we know that our application is only read, we can let shelve open the db by read-only mode.

Mport Shelvef = Shelve.open (' shelve_file ', flag= ' r ') existing = f[' key ']f.close () print (existing)

Since shelve does not record any modifications to the persisted object by default, we need to modify the default parameters at Shelve.open () or the object's modifications will not be saved.

# set Writebackimport shelvef1 = Shelve.open (' shelve_file ') print (f1[' key ') f1[' key ' [' new_value '] = ' This is not here Before ' f1.close () F2 = Shelve.open (' Shelve_file ', writeback=true) print (f2[' key ') ' f2[' key ' [' new_value '] = ' this is Not here before ' F2.close ()

There are pros and cons to the writeback approach. The advantage is to reduce the probability of our error, and to make the object's persistence more transparent to the user, but this method is not required in all cases, first, after using writeback, shelf in open () will increase the additional memory consumption, and when the DB in close () , each object in the cache is written to the DB, which also brings additional wait times. Because shelve has no way of knowing which objects in the cache have been modified and which objects have not been modified, all objects will be written.

Python full stack development "Tenth" Python Common Module II (time, random, OS, SYS, and serialization)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.