Python's common modules (re, time, Random,os,sys, serialization module) (DAY20)

Source: Internet
Author: User
Tags month name shuffle string format

I. Time module

# Common Methods 1. Time.sleep (secs) (thread) Delays the specified time run. Unit is seconds. 2. Time.time () Gets the current timestamp

Three ways to represent time in Python: timestamp, tuple (struct_time), formatted time string "Timestamp is the time that the computer can recognize, time string is the time the person can recognize, and the tuple is used to manipulate the time"

#Import Time Module>>>Import Time#time Stamp>>>time.time ()1500875844.800804#Time String>>>time.strftime ("%y-%m-%d%x")'2017-07-24 13:54:37'>>>time.strftime ("%y-%m-%d%h-%m-%s")'2017-07-24 13-55-04'#time tuple: localtime converts a timestamp to the struct_time of the current time zonetime.localtime () time.struct_time (Tm_year=2017, tm_mon=7, tm_mday=24, Tm_hour=13, tm_min=59, tm_sec=37, Tm_wday=0, tm_yday=205, tm_isdst=0)

Formatting the representation of a time string

%y Two-digit year representation (00-99)%Y Four-digit year representation (000-9999)%m Month (01-12)One day in%d months (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 Day of the Year (001-366)%p equivalent of local a.m. or P.M.%u days of the year (00-53) Sunday for the beginning of the week%w Week (0-6), Sunday for the beginning of the week%W number of weeks in the year (00-53) Monday for the beginning of the week%x Local corresponding date representation%X Local corresponding time representation%Z name of the current time zone%% %number itself python in the time date format symbol:
View Code

Two. Random module

>>>ImportRandom#Random Decimals>>> Random.random ()#decimals greater than 0 and less than 10.7664338663654585>>> Random.uniform (1,3)#decimals greater than 1 and less than 31.6270147180533838#random integers>>> Random.randint (1,5)#integer greater than or equal to 1 and less than or equal to 5>>> Random.randrange (1,10,2)#integers greater than or equal to 1 and less than 3#randomly selects a return>>> Random.choice ([1,' at', [4,5]])##1或者23或者 [4,5]#Randomly select multiple returns, the number returned is the second parameter of the function>>> Random.sample ([1,' at', [4,5]],2]##列表元素任意2个组合[4, 5],' at']#Shuffle List Order>>> item=[1,3,5,7,9]>>> Random.shuffle (item)#Shuffle Order>>>item[5, 1, 3, 7, 9]>>>random.shuffle (item)>>>item[5, 9, 7, 1, 3]
Import Random def V_code ():     "'     for  in range (5):        num=random.randint (0,9)        Alf=CHR (Random.randint (65,90))        Add=random.choice ([num,alf])        code="". Join ([Code,str (add)])     return  codePrint(V_code ()) generates a verification code
generate random Verification code

Three. OS Module

OS module is an interface for operating system interaction

" "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, is the time of the most recent metadata change, and on other systems (such as Windows) is the time of creation (see the documentation for the platform for more information). Stat Structure
View Code

Four. SYS module

SYS module is an interface that interacts with the Python interpreter

SYS.ARGV           command line argument list, the first element is the program itself path Sys.exit (n)        exits the program, exit normally (0) sys.version        Gets the version information of the Python interpreter Sys.maxint         the largest int value Sys.path           returns the search path for the module, using the value of the PYTHONPATH environment variable when initializing Sys.platform       Returns the operating system platform name

Five. Serialization module

----------the process of converting an original list, dictionary, and other content into a string is called serialization.

Purpose of serialization

1. Persist the custom object in some form of storage; 2. Transfer objects from one place to another. 3, make the program more maintenance.

JSON module

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

ImportJsondic= {'K1':'v1','K2':'v2','K3':'v3'}str_dic= Json.dumps (DIC)#Serialization: Converting a dictionary into a stringPrint(Type (str_dic), str_dic)#<class ' str ' > {"K3": "V3", "K1": "V1", "K2": "V2"}#Note that the string in the dictionary of the string type converted by JSON is represented by ""Dic2= Json.loads (Str_dic)#deserialization: Converts a dictionary of a string format into a dictionary#Note that the string in the dictionary of string types to be processed with the JSON loads function must be represented by ""Print(Type (DIC2), Dic2)#<class ' dict ' > {' K1 ': ' v1 ', ' K2 ': ' v2 ', ' K3 ': ' V3 '}List_dic= [1,['a','b','C'],3,{'K1':'v1','K2':'v2'}]str_dic= Json.dumps (List_dic)#you can also handle nested data typesPrint(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 '}]Loads and dumps
Dumps and loads
Importjsonf= Open ('Json_file','W') DiC= {'K1':'v1','K2':'v2','K3':'v3'}json.dump (dic,f)#The dump method receives a file handle and translates the dictionary directly into a JSON string to write to the fileF.close () F= Open ('Json_file') Dic2= Json.load (f)#The load method receives a file handle, directly converting the JSON string in the file into a data structure to returnf.close ()Print(Type (DIC2), dic2) load and dump
load and dump

Pickle

JSON & Pickle Modules

Two modulo fast for serialization:

JSON: Used for conversions between string and Python data types

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

The Pickle module provides four functions: dumps, dump (serialize, save), loads (deserialization, read), load (not only serializable dictionary, list ... can serialize arbitrary data types in Python )

ImportPickledic= {'K1':'v1','K2':'v2','K3':'v3'}str_dic=pickle.dumps (DIC)Print(Str_dic)#A string of binary contentDic2=pickle.loads (str_dic)Print(DIC2)#DictionaryImportTimestruct_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) Pickle
View Code

At this time witty you have to say again, since pickle so strong, why still learn JSON?
Here we want to illustrate that JSON is a data structure that all languages can recognize.
If we have a dictionary or serialized into a JSON file, then the Java code or JS code can also be used.
But if we use pickle to serialize, other languages can't read what it is.
So, if your serialized content is a list or a dictionary, we highly recommend that you use the JSON module
But if for some reason you have to serialize other data types, and in the future you will also use Python to deserialize this data, then you can use pickle

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.

ImportSHELVEF= Shelve.open ('Shelve_file') f['Key'] = {'int': 10,'float': 9.5,'string':'Sample Data'}#directly to the file handle, you can deposit dataf.close ()ImportSHELVEF1= Shelve.open ('Shelve_file') Existing= f1['Key']#when you take out the data, you just need to get it directly with key, but if key doesn't exist, it will be an error.f1.close ()Print(existing) shelve
View Code

Python's common modules (re, time, Random,os,sys, serialization module) (DAY20)

Related Article

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.