A rough summary of the various modules (Time,re,os,sys, serialization, Pickle,shelve.#!json)

Source: Internet
Author: User
Tags format definition month name

Collections Extended Data Type * * *

Re regular correlation operation regular Match String * * *

Time-related three formats: timestamp, format time (string), time tuple (structured time).
***
"' Python
#时间戳: Timestamp The offset is calculated in seconds starting January 1, 1970 00:00.
Time.time ()

#格式化时间: (Format String) 1992-12-10
%y-%m-%d_%a%h:%m:s
%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 a locally simplified month name
%B Local Full month name
%c Local corresponding date representation and time representation
%j Day of the Year (001-366)
%p the equivalent of a local a.m. or p.m.
%u weeks of the year (00-53) Sunday is the beginning of the week
%w Week (0-6), Sunday for the beginning of the week
%W Week of the Year (00-53) Monday is the beginning of the week
%x Local corresponding date representation
%x Local corresponding time representation
%Z the name of the current time zone
Percent% of the number itself

#时间元组: (structured time) stack_time contains nine elements: the day of the month and the second of this year, the first few weeks of the year.
```
```
#时间戳 time tuple (structured time)
Time.gmtime (#填时间戳) #UTC时间
Time.localtime (#填时间戳) #当地时间

#时间元组-Time Stamping
Time.mktime (#时间元组)

#时间元组-To-string
Time.strftime (' format definition ', ' time tuple ') #若不传参数, displays the current time
Time.strftime ("%y-%m-%d", Time.localtime (1500000000))
' 2017-07-14 '

Import time
#字符串-to-time tuples
#time. Strptime (' Time string ', ' string format ')
L = time.strptime (' 1992-10-10 ', '%y-%m-%d ')
Print (L)
#时间元组-To-string
# time.strftime (' format definition ', ' time tuple ') #若不传时间元组, the current time is displayed.
L1 = time.strftime ('%y-%m-%d ')
Print (L1)

L2 = Time.strftime ('%y-%m-%d ', Time.localtime (1500000000))
Print (L2)

```


OS and OS-related * * *

SYS and Python interpreter interaction * * *

The serialization module converts data structures in Python into str.
What does serialization mean? The process of converting the original dictionary/list and other content into a string * * *

JSON JSON general-purpose data structures in Python are dictionaries and lists * * *

# # Json:four_leaf_clover:

Used to convert between a string and a Python data type, because JSON represents a string

The JSON module provides four methods

| Method | Description |
| ----- | ----------------------------- |
| Dump | Receives a file handle and converts the original data type to a string to write to the file |
| Load | Receives a file handle that converts a string in a file to the original data type returned |
| Dumps | Receives a data type and converts it to a string |
| Loads | Receives a string and converts it to the original data type |

Dump and Load instances

"' Python
# import JSON module
Import JSON
# Create a file handle
f = open (' Json_file ', ' W ')
# Create a dictionary
DiC = {' K1 ': ' v1 ', ' K2 ': ' V2 '}
# Convert a dictionary to a string to write to a file
Json.dump (DIC,F)
# Close File
F.close ()
# Create a file handle
f = open (' Json_file ')
# Read the string in the file and convert it to the original data type
Dic2 = Json.load (f)
# Close File handle
F.close ()
# Print Type and results
Print (Type (DIC2), Dic2)
# <class ' dict ' > {' K1 ': ' v1 ', ' K2 ': ' V2 '}
```

Dumps and loads instances

"' Python
# import JSON module
Import JSON
# Create a new list
LST = [' 1 ', ' 2 ', ' 3 ', ' 4 ']
# Convert the list to a string and use J_d to receive the return value
J_d = Json.dumps (LST)
# Convert a string to the original data type and use j_s to receive the return value
j_s = Json.loads (j_d)
# Print the value of j_d and type
Print (J_d,type (j_d))
# ["1", "2", "3", "4"] <class ' str ' >
# Print the value of j_s and type
Print (J_s,type (j_s))
# [' 1 ', ' 2 ', ' 3 ', ' 4 '] <class ' list ' >
```

Special cases of loads

"' Python
# import JSON module
Import JSON
# Create a string that is internally a dictionary
dic_s = "{' K1 ': ' v1 ', ' K2 ': ' v2 ', ' K3 ': 3}"
# Convert a string into a dictionary
Json.loads (dic_s)
# An error occurred in the interpreter
# json.decoder.JSONDecodeError:Expecting property name enclosed in double quotes:line 1 column 2 (char 1)
‘‘‘
For error reasons, strings in a dictionary of type string must be represented by "" When using JSON's loads function.
That is, the above dic_s should be changed to ' {' K1 ': ' v1 ', ' K2 ': ' v2 ', ' K3 ': 3} '

Conclusion: When using JSON's loads function, strings in a dictionary of type string must be represented by ""
‘‘‘
```

Ps:json can be used for data exchange between different languages

Pickle is dedicated in Python and can be serialized on any data type, resulting in bytes type * * *

Shelve only provides an open method that operates a bit like a dictionary. * * *

# # Pickle:four_leaf_clover:

Convert between Python-specific types and Python data types

The Pickle module also offers four methods, like JSON dumps, dump, loads, load

Since Pickle is a unique type for Python, the load and loads methods support not only dictionaries, but also lists, which can serialize arbitrary data types in Python

"' Python
-------Dumps and loads--------
# import Pickle Module
Import Pickle
# Create a dictionary
DiC = {' K1 ': ' v1 ', ' K2 ': ' V2 '}
# Convert dictionaries into binary content
P_d = Pickle.dumps (DIC)
# Convert binary content into a dictionary
p_l = Pickle.loads (p_d)
# Print P_d
Print (P_d)
# b ' \x80\x03}q\x00 (x\x02\x00\x00\x00k2q\x01x\x02\x00\x00\x00v2q\x02x\x02\x00\x00\x00k1q\x03x\x02\x00\x00\x00v1q \x04u. '
# Print the type of p_d
Print (Type (p_d))
# <class ' bytes ' >
# Print p_l
Print (p_l)
# {' K2 ': ' v2 ', ' K1 ': ' v1 '}
# Print the type of p_l
Print (Type (p_l))
# <class ' Dict ' >
---------Dump and load---------
# Create a file handle
f = open (' Pickle_file ', ' WB ')
# Write Content
Pickle.dump (' Lyon ', f)
# Close File
F.close ()
# Create a file handle
f = open (' Pickle_file ', ' RB ')
# Read the content
P_f = Pickle.load (f)
# Close File
F.close ()
# Print
Print (P_f)
# Lyon
```

* * But Pickle can only serialize data in Python, and other languages will not be able to read it when deserializing. * *, so we generally recommend using JSON

# # Shelve:four_leaf_clover:

Shelve is also a serialization tool that Python provides to us, which is simpler than pickle.

Shelve only provides us with an open method, which is accessed using key, and is similar to the dictionary.

"' Python
# import Shelve Module
Import shelve
# Shelve provides open methods
f = shelve.open (' Shelve_file ')
# directly manipulate the file handle, it can be written to the file
f[' key ' = {' int ': Ten, ' float ': 9.5, ' string ': ' Sample data '}
# Close File
F.close ()
# Open File
F1 = Shelve.open (' Shelve_file ')
# directly with the key value, key does not exist on the error
existing = f1[' key ']
# Close File
F1.close ()
# Print Results
Print (existing)
# {' Float ': 9.5, ' int ': Ten, ' String ': ' Sample data '}
```

Shelve does not support multiple applications to operate on a single database at the same time, so when we know that our application is only operating, we can set the parameters of the Shelve.open () method to do

Shelve.open (filename, flag= ' C ', Protocol=none, Writeback=false)

"' Python
Import shelve
# flag parameter for set operation mode, r to set read-only mode
f = shelve.open (' shelve_file ', flag= ' R ')
existing = f[' key ']
F.close ()
Print (existing)
```

The ' writeback ' parameter can reduce the probability of our error, and make the object's persistence more transparent to the user; But this approach is not required in all cases, first, after using writeback, shelf will increase the additional memory consumption when open (), and when the database is in close () writes every object in the cache to the database, 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
Import shelve
F1 = Shelve.open (' Shelve_file ')
Print (f1[' key ')
f1[' key ' [' new_value '] = ' This is not here before '
F1.close ()
# set Writeback
F2 = Shelve.open (' Shelve_file ', writeback=true)
Print (f2[' key ')
f2[' key ' [' new_value '] = ' This is not here before '
F2.close ()
```

A rough summary of the various modules (Time,re,os,sys, serialization, Pickle,shelve.#!json)

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.