Python Learning DAY16 Module

Source: Internet
Author: User
Tags string back

" "module: Contains Python definition and declaration of the file, a py file is a Module 1, built-in module Python interpreter comes with Module 2, extension module, the module developed by Daniel, need to download using 3, custom module of the module itself * * * * Serialization module JSON Pickle Shelvejson can be used to serialize data types in different languages into strings, support str,list,dict,bool These data types pickle only available in the Python language, and support all Python data types to be serialized as strings. We can also use the object as the data type is the data type of the owning class shelve is also available only for Python, dictionary-like operations, you can save the data type as a dictionary key to a file" "#JSON dumps ()/loads () Dump ()/load ()#dumps (data type such as dictionary)/loads (serialized string) dump (data type, file handle)/load (file handle)ImportJsondic= {"name":"Alex"," Age": 18}ret= Json.dumps (Dic,ensure_ascii=false)#Convert the dictionary to a serialized string, and add the Ensure_ascii parameter to make the Chinese display in the stringDic2 = json.loads (ret)#Converts a serialized string back to the original data typeImportJsondic= {"name":"Alex"," Age": 18}with Open ("Json_file", encoding='Utf-8', mode='W') as F1:json.dump (DIC,F1)#Convert a dictionary to a serialized string and save it in a fileWith open ("Json_file", encoding='Utf-8') as F2:Print(Json.load (F2))#Converts a serialized string back to the original data type#Note that json.dump/load can only read one data, and if there are multiple dictionaries that cannot be written into the file, we can do it by other means#save multiple data to a fileImportJsondic1= {"name":"alex1"," Age": 18}dic2= {"name":"Alex2"," Age": 18}dic3= {"name":"alex3"," Age": 18}with Open ("Json_files", encoding='Utf-8', mode='W') as F1:s1=json.dumps (dic1) S2=Json.dumps (dic2) S3= Json.dumps (DIC3)#serialize the dictionary to a string using dumps () firstF1.write (s1+'\ n'+s2+'\ n'+s3+'\ n')#line Wrap Save stringWith open ("Json_files", encoding='Utf-8') as F2: whileTrue:Try:             forLineinchF2:Print(Json.loads (line))#There is no need to deal with strip ' \ n ', loads will automatically ignore        exceptEoferror:#Eoferror error is thrown when the serialized string in the file is read, here we use try ... except ... Handling Exceptions \             Break           #encounter that break, how to know what mistakes we will encounter, it is not possible to remember, can deliberately produce this error, \                            #and then find the statement for the Python interpreter to make an error .            #{' name ': ' Alex1 ', ' age ':#{' name ': ' Alex2 ', ' age ':#{' name ': ' Alex3 ', ' age ':#the usage of pickle is basically the same as JSON, and is also dumps (data type)/loads (serialized string) dump (data type, file handle)/load (file handle)#A little different is that pickle dump ()/load () can read multiple serialized stringsImportPickledic1= {"name":"alex1"," Age": 18}dic2= {"name":"Alex2"," Age": 18}dic3= {"name":"alex3"," Age": 18}with Open ("Pickle_files", mode='WB') as F1:#Pickle whether dumps or dump serialized strings are bytes types, read-write files can only use WB,RB mode and cannot have encoding modepickle.dump (DIC1,F1) pickle.dump (DIC2,F1) pickle.dump (DIC3,F1) with open ("Pickle_files", mode='RB') as F2: whileTrue:Try:            Print(Pickle.load (F2))#just read it and it will automatically read it one by one        exceptEoferror: Break#to save an object of a class using pickle#1, first write to the object in the fileImportPickleclassA:def __init__(self,name,age): Self.name=name Self.age= AgedefWork (self):Print('%s is tapping code'%self.name) A1= A ('Alex', 18) A2= A ('Sylar', 20) with open ('Pickle_obj', mode='WB') as F1:pickle.dump (A1,F1) pickle.dump (A2,F1)#now our file Pick_obj has saved the object of a a1,a2, but because it is our own definition of the class, the object cannot be separated from the definition of the class, \#so there are two ways to use the objects in the file below, one is to keep the definition of Class A in the current file, one to put the definition of Class A in other py files, \#by referencing the py file as a module, there is a class that defines the#* * * The use of objects, method oneImportPickleclassA:def __init__(self,name,age): Self.name=name Self.age= AgedefWork (self):Print('%s is tapping code'%self.name) Li=[]with Open ('Pickle_obj', mode='RB') as F2: whileTrue:Try: Li.append (Pickle.load (F2))exceptEoferror: Break forIinchLi:Print(i.name,i.age)#Alex#Sylar#* * * Use of objects, method twoImportPickle fromGuo123ImportA#Put the definition of Class A in the guo123.py fileLi =[]with Open ('Pickle_obj', mode='RB') as F2: whileTrue:Try: Li.append (Pickle.load (F2))exceptEoferror: Break forIinchLi:Print(i.name,i.age)#Alex#Sylar#***shelve***#shelve provides us with an open method, which is accessed using key and is similar to the dictionary .ImportShelvedic= {'int': 10,'float': 9.5,'string':'Sample Data'}f= Shelve.open ('Shelve_file') f['Key1'] =dicf.close ()ImportSHELVEF1= Shelve.open ('Shelve_file') Get_dic= f1['Key1']Print(get_dic)#{' int ': Ten, ' float ': 9.5, ' string ': ' Sample data '}#It is not possible to modify or add the key-value pairs that we have taken, if we want \#Add a parameter to modify or add a writeback=trueF2 = Shelve.open ('Shelve_file', writeback=True)Print(f2['Key1'])#{' int ': Ten, ' float ': 9.5, ' string ': ' Sample data '}f2['Key1']['New_value'] ='This is not here before'Print(f2['Key1'])#{' int ': Ten, ' float ': 9.5, ' string ': ' Sample data ', ' new_value ': ' This is not here before '}f2.close ()

Python Learning DAY16 Module

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.