Learn day6

1. Module

1.1 the pickle module
# ### the pickle sequencing module Import the pickle "" " Serialization: data can not be stored directly in the memory becomes deserialization: to restore the original data into a data format serialize serialized unserialize deserialization " "" # under normal circumstances, can not be directly to the container type in which the file data is stored directly "" " with Open (" ceshi.txt ", MODE =" W ", encoding =" UTF-. 8 ") AS FP: LST = [l, 2,3] fp.write (LST) "" " # dumps into a sequence of arbitrary objects bytes LST = [1,2,3,4,5 ] RES = the pickle.dumps (LST) Print (RES ) # loads arbitrary bytes deserialized into original data RES = the pickle. loads(res) print(RES, of the type (RES)) # serialization function DEF FUNC (): Print ( " I'm a function " ) RES = pickle.dumps (FUNC) Print (RES) # deserialization function FUNC = pickle.loads (RES ) FUNC () # sequence iterators from Collections Import the iterator, the Iterable IT = ITER (Range (10 )) Print (the isinstance (IT, the iterator)) RES = the pickle.dumps (IT) Print (RES) RES = The pickle.loads (RES) Print (RES) for I in RES: Print (I) # dumps and loads the data in the file setvar = { " A " , " B " } with Open ( " ceshi.txt " , MODE = " RB + " ) AS FP: RES = the pickle .dumps (setvar) fp.write (RES) # read the contents when first beginning of the line the cursor file. fp.seek (0) RES2 = fp.read () Print (RES2) setvar = the pickle.loads ( RES2) Print (setvar, of the type (setvar)) # Dump written after the object is serialized to the file-like Object (ie, file objects) DEF func2 (): Print ( " I am func2 " ) with Open ( " ceshi02.txt " , the MODE = " wb " ) AS fp: # parameter 1: to serialize the data parameter 2: corresponding to the file object the pickle.dump (func2, FP) # Load the contents of the file-like Object (i.e., file objects) is out, the original data is deserialized into with open ( " ceshi02.txt " , MODE = " RB " ) AS FP: FUNC = the pickle.load (FP) # call the function FUNC () # the pickle module can serialize all data types.

1.2 json module

### json # 
Import json
"" "
json data sequence may be converted into a string
of data format json, it allows all programming languages are able to identify
the data type restrictions: bool float int list tuple dict str none
"" "

# first group: dumps and loads to serialize or deserialize the string
" ""
ensure_ascii = True set whether to display the Chinese ensure_ascii = False display Chinese
sort_keys = True key dictionary sorted by ASCII
"" "
DIC = {" name ":" Li Zuqing "," age ": 58, " sex ":" man "," family ": [" father "," mother "," sister "," sister "]}
RES = json.dumps (DIC, ensure_ascii = False, sort_keys = True)
Print (RES, type (RES))

DIC = json.loads (RES)
Print (DIC, type (DIC))

# the second group: dump load and for data storage
dic = { "name":"李祖清","age":58,"sex":"man","family":["爸爸","妈妈","姐姐","妹妹"]}
with open("ceshi03.json",mode="w",encoding="utf-8") as fp:
The json.dump (DIC, FP, ensure_ascii = False)

with Open ( "ceshi03.json", MODE = "R & lt", encoding = "UTF-. 8") AS FP:
DIC = the json.load (FP)

Print (DIC, of the type (dic))

# json difference between the two modules and pickle?

# json usage characteristics:
"" "
json continuously dump, but not continuously load
load can load only once, it is a one-time all the data as a whole transformation
may be used to resolve loads
"" "
DIC1 = { 'A':. 1," B ": 2}
DIC2 = {" C ":. 3," D ":}. 4

with Open (" ceshi04.json ", = MODE "W", encoding = "UTF-. 8") AS FP:
The json.dump (DIC1, FP)
fp.write ( "\ n-")
The json.dump (DIC2, FP)
fp.write ( "\ n-" )

# error can only load one, it is a one-time conversion of all the data.
"" "
with open("ceshi04.json",mode="r",encoding="utf-8") as fp:
res = json.load(fp)
print(res)
"""
# 解决方式
with open("ceshi04.json",mode="r",encoding="utf-8") as fp:
for line in fp:
res = json.loads(line)
print(res)


# pickle 用法特征:
import pickle
"""
pickle 可以连续dump,也可以连续load
"""
dic1 = {'a':1,"b":2}
dic2 = {"c":3,"d":4}

with open("ceshi05.pkl",mode="wb") as fp:
pickle.dump(dic1,fp)
pickle.dump(dic2,fp)

with open("ceshi05.pkl",mode="rb") as fp:
try:
while True:
dic = pickle.load(fp)
print(dic)
except:from the Collections Import Iterator# file object is an iterator it? Yes!Print (333)
Pass




Print (isinstance (fp, Iterator))

"" "
try ... except ...
the offending code directly try to uninstall this block of code which,
if abnormal, go directly except this block of code to prevent an error occurs terminate the program.
try :
Print (wangwendashuaiguo)
the except:
Pass
"" "


# summary:
" ""

# json and pickle difference between the two modules:
(1) type data is serialized after json str, all programming languages are identified,
but only ( BOOL a float int) (STR dict None List tuple)
JSON Load not continuous, only one out of all of the data
(2) after the data type is bytes pickle serialization,
all types of data can be transformed, but only between the python the storage transport.
the pickle continuous load, multiple sets of data into a single file,

"" "

1.3 Random module

# ### random random module 
import random # random () Gets the fraction between 0-1 randomized (left and right open-closed) 0 <= X <. 1
RES = random.random ()
Print (RES)

#randrange () random Gets an integer in the specified range (including the start value, the end does not contain a value, the value of the interval)

# 012 is not included. 3
RES = random.randrange (. 3)
Print (RES)

# ~. 4. 1
RES = random.randrange (. 1, . 5)
Print (RES)

# 1. 4. 7
RES random.randrange = (1,10,3)
Print (RES)

#randint () randomly generates a random integer (two parameters must) (Learn) within a specified range of
# 12 . 4. 3
RES = the random.randint (l, 4)
Print (RES)
# 1 is for the randint or to 3 is wrong, only two parameters to
# res = random.randint (1,10,3)


#uniform () Gets a random decimal specified range (left and right open-closed). 1 <= X <. 3
RES = random.uniform (l, 3) # written recommendation
Print (RES)
RES = random.uniform (2, -1 ) # Not recommended
Print (RES)

# 2 = A -1 = B
# + A return (BA) * self.random () (0 <= X <. 1)
# self.random () # -1 <X <= 2
# 2 + (-1-2) = 2 * 0
# 2+ (-1-2). 1 * 2 = - = -1. 3
# 2


#choice () Gets the value of a random sequence (one of many)
LST = [ "Shu will "," Guo Yimeng "," Yin Yan "," Liao Pingping "]
RES = The random.choice (LST)
Print (RES)

# custom Choice
DEF MyChoice ():
length = len (LST)
RES = Random. randrange (0, length)
return LST [RES]
Print (MyChoice ())

#sample () Gets the value of a random sequence (multi-multi-select) [Back]
LST = [ "Shu will", "Guo Yimeng" "Yin Yan", "Yin Yan 2", "Liao Pingping", "Liu Lu"]
LST = random.sample (LST,. 3)
Print (LST)

#shuffle () disrupted random sequence of values (direct disrupted prosequence)
LST = [1,2,3,4,5]
random.shuffle (LST)
Print (LST)

# random codes
DEF yanzhengma ():
strvar = ""
for I in Range (. 4):
# Z A ~ 97 ~ 122 acquires lowercase
RES1 = CHR (random.randrange (97,123))
# A ~ the Z 65 to obtain 90 uppercase
RES2 = CHR (random.randrange (65,91))
# 0 to 9, 0 to 9 ten numbers acquired
RES3 = random.randrange (0,10)
# of possible characters into the list among
lst = [RES1, RES2, RES3]
# string concatenation
strvar = + STR (The random.choice (LST))
# returns a string
return strvar

RES = yanzhengma ()
Print (RES)

1.4 OS module

# ### os operating system module 
Import OS

#system () execution system in python
# the os.system ( "mspaint in")
# the os.system ( "the ipconfig")

#popen () returns the object execution system, the string is read by the read method, will not be garbled
obj = os.popen ( "ipconfig")
Print (obj.read ())

#listdir () Gets the name list of the specified folder in all content
"" "
. represents current path
.. represents the path of a
"" "
RES = the os.listdir (". ")
Print (RES) # [ '1.py', '2.py', '20190728_1.json_pickle.mp4', '3.py', '4.py', 'ceshi.txt', 'ceshi02.txt', 'ceshi03.json', 'ceshi04.json', 'ceshi05.pkl', 'ceshi_shengyin.mp4', 'part10 .md ',' part11.md ']

#getcwd () Gets the default path of the current file
res = os.getcwd ()
Print (RES) # D: \ weekend four \ L006
Print (__ file__) # full path (plus file name)




# os.mkdir create directories (folders)
Os.mkdir # ( "ceshi100")
# os.rmdir delete directories (folders)
# os.rmdir ( "ceshi100")
# os.rename on the file, directory, rename
# os.rename ( "ceshi100", " ceshi200" )

#copy (src, dst) # copy file permissions and content
# Import shutil
# shutil.copy ( "ceshi02.txt", "ceshi333.py")


#chdir () to modify the default path of the current file work
# os.chdir ( r "D: \ weekend four \ L005")
# os.mkdir ( "ceshi200")

#environ obtain or modify environment variables
# Print (os.environ)
# os.system ( "QQScLauncher")

# Environ returns a dictionary by variable path environment, the path is added, at the time of executing the command, a path to take to find a, if the direct execution is found, contrary error
'' '
Print (os.environ [ "the pATH"])
os.environ [ "the pATH" ] + = r "" "; C: \ Program Files (x86) \ Tencent \ QQ \ Bin" ""
The os.system (" QQScLauncher.exe ")
'' '

# - OS module properties
#name identifier acquisition system Linux, MAC -> Windows POSIX -> NT
Print (The os.name)
#sep symbol acquired route into Linux, MAC -> / Window-> \
Print (os.sep)
#linesep acquisition system line breaks linux, mac -> \ n window -> \ r \ n or \ n-
Print (the repr (os.linesep))

 

Guess you like

Origin www.cnblogs.com/NGU-PX/p/11294439.html