We learned before json and pickle modular These are all serialized modules , Let's talk about a serialization be called shelve

You must have a question , This thing is similar to that. Why should we talk about it . Because this module is relatively simple , And you need to use a database when storing data later , But when there is less data, we can not interact with the database through the network . Just use our local files

Okay , Let's see how easy this is .

First of all, we need to import shelve This module , And then it's like operating a file . Okay, let's try

import shelve
f ='sss')

So we created three files , I'm lost when I listen to three documents , Don't worry. Let's look down

'name', (0, 28)
This bak No other function is the backup file
�]q (KKK}qX 1qKse.
'name', (0, 28)

what , What are these , Are you thinking that ?? This is us. windows Content obtained by creating files under the system , Don't worry about it . But remember to add something without a hand owe

We just mentioned windows Here are the three , What is an apple , Apple's, Okay, it doesn't matter . We just need to know how to use it .

We just need to use the dictionary to operate

import shelve
f ='sss')
f['name'] = [1,2,3,{'1':2}]

The above operation is to add a key value pair , The key here has a requirement that the key must be of string type . The value is python Data of type not required

We will now write a dictionary to the file , Let's change it. py The file value needs to be opened to use the dictionary . You'll think about it . This and json/pickle What's the difference? There's no difference in this concept , It is to persist an object into a file .

Let's think about if I need to increase the key value frequently in the later period , If used pickle and json Does it need to be done once dump And then they're adding

Let's take a look first pickle Add key value pair to dictionary of

import pickle
# First we need to open a file
f = open('ss','wb')
dic = {'name':' Bao Yuan '}
# take dic Dictionary serialized here ss In file
pickle.dump(dic,f) # Then open this file
f1 = open('ss','rb')
# Reverse the contents of this file
dics = pickle.load(f1)
# Attach a new variable
print(dics) dics['age'] = 18
# Then add values
f2 = open('ss','wb')
# In serializing the latest dictionary
dics = pickle.dump(dics,f2) f3 = open('ss','rb')
dics = pickle.load(f3)
# Finally, the dictionary will be printed after the reverse sequence

There's no problem with that , But let's see shelve How did it happen

import shelve
f ='sss')
f['name'] = [1,2,3,{'1':2}]
# We can see it directly after adding , Not many times dump and load 了
f['age'] = 20

Comparison of previous and next , Do you think shelve It's quite simple , That's not all , Actually shelve This module is a open And a dictionary

Think about the functions in the dictionary , What does it do ..

But I have to say that it has its problems , The problem with it is that you can't directly view what's in the dictionary , We want to see what functions are in this dictionary

We need to cycle this dictionary

 Mode one 
import shelve
f ='sss')
for k in f:
Running results :name Mode two
import shelve
f ='sss')
for k in f.keys():
Running results :name

As like as two peas in our dictionary. , If we check f.keys() It's not what we expected , This can't be viewed only for loop

Sometimes we want to modify the dictionary name Corresponding value , What should we do at this time

import shelve
f ='sss')
f['name'] = ' Bao Yuan '
f['name'] = 'meet'
print(f['name']) Running results :
Bao Yuan

We are only one step away from success now , What is wrong? ?? This thing will be used there ?

If there is no strong demand for this thing , We can use this way to serialize , He was based on pickle Realized .

Let's take this. shelve There is a hole in the module. You need to pay attention to the failure of writing back the file , You just need to open Write a writeback=True This is write back .


Today is a welfare day , I just told you a module for quick use of serialization , I'm teaching you a module shutil

This module is for the operation of files and folders , It also has the function of compressing package . No more bullshit. Let's import this module now

import shutil

Let's see what the file does first

import shutil

Copy files , You can specify your own mode and encoding

import shutil
shutil.copyfile(r'D:\untitled2\a\', 'f2.log') # Target file must exist

Copy files , Put a source file in the first parameter , The second parameter puts a name of the file to copy to , Mode doesn't matter , The default encoding method is utf-8

Copy only permission . Content 、 Group 、 No change in users

shutil.copymode('f1.log', 'f2.log') # Target file must exist 

Copy only state information , Include :mode bits, atime, mtime, flags

shutil.copystat('f1.log', 'f2.log') # Target file must exist 

Copy files and permissions

import shutil
shutil.copy2('f1.log', 'f2.log')

Copy folder recursively

1 import shutil
3 shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
# Destination directory cannot exist , Pay attention to that folder2 Directory parent directory should have writable permission ,ignore Means to exclude

Recursively delete files

import shutil

Recursively remove files

import shutil
shutil.move('folder1', 'folder3')

Create a zip and return the file path , for example :zip、tar

base_name: Filename of the package , It can also be the path of the compressed package . When it's just a filename , Save to current directory , Otherwise save to the specified path ,
Such as data_bak => Save to current path
Such as :/tmp/data_bak => Save to /tmp/
format: Type of compression package ,“zip”, “tar”, “bztar”,“gztar”
root_dir: Folder path to compress ( Default current directory )
owner: user , Default current user
group: Group , Default current group
logger: For logging , Usually logging.Logger object # take /data Package and place the current program directory under
import shutil
ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data') # take /data Package and place files under /tmp/ Catalog
import shutil
ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')

shutil The processing of the compressed package is called ZipFile and TarFile Two modules , detailed :

zipfile Compression and decompression

import zipfile
# Compress 
z = zipfile.ZipFile('', 'w')
z.close() # decompression
z = zipfile.ZipFile('', 'r')

tarfile Compression and decompression

import tarfile
# Compress'/tmp/egon.tar','w')
t.close() # decompression'/tmp/egon.tar','r')

The root of all evil - Python More articles on module 2

  1. The root of all evil - Python Module one

    serialize Let's learn about serialization today , What is serialization ? Put the original dictionary . The process of converting a list to a string is called serialization . Why have serialization modules : such as , We are python A data calculated in the code needs to be used by another program ...

  2. The root of all evil - Python Data type 2

    list 列 Table Introduction   列 Table is python One of the basic data types of , Other programming languages have similar data types . such as JS The number in Group , java Arrays in etc . It is a [ ] Cover up , Each element uses ' , ' Separate and can store each ...

  3. Python - modular ( Two )

    Catalog Python - modular ( Two ) re re The following method logging os Python - modular ( Two ) re re Module provides regular expression related operations Introduction to the main characters : . wildcard , Anything but newline ...

  4. The root of all evil -python Basic data type

    The root of all evil - Basic data type (dict) The main content of this section : A brief introduction to the dictionary Dictionary addition, deletion, search and other operations 3. Nesting of dictionaries ⼀ One . A brief introduction to the dictionary Dictionaries (dict) yes python Zhongwei ⼀ One ⼀ A mapping type . He is with { ...

  5. The root of all evil - Python Application of package

    Introduction to package The bags you heard , It's not the bag that women are crazy about , Let's see what kind of bag this is Official explanation : Packages are a way of structuring Python’s module namesp ...

  6. The root of all evil - Python Custom module

    Custom module Let's learn about the custom module today ( That's to say, private customization ), We want to customize the module , First of all, we need to know what module is A function encapsulates a function , For example, there is a software , It's not possible to write all programs to one file , So we should divide the documents , Group ...

  7. The root of all evil - Python Basics

    Python brief introduction python Founded by Guido · Van rosum (Guido van Rossum).1989 Christmas period of , Guido · Van rosum ( Chinese name : Uncle GUI ) To spend time in Amsterdam , Determined to develop a new script interpreter ...

  8. python Module two (os,json,pickle)

    ################################# summary ##################### os Commonly used os.makedirs('baby/ Angola / tesla / Huang Xiaoming ') os.mkd ...

  9. The root of all evil - Python The development of specification

    The development of specification What is a development specification ? Why is there a development specification ? You now include some of the programs you wrote before , So-called ' project ', It's all in one py Completed under the document , The amount of code is hundreds of lines , You think it's OK , Very good . But real backend development projects , Systems, etc , Less ...

Random recommendation

  1. Android JSON、GSON、FastJson Encapsulation and analysis of

    Statement : 1. This post only provides code , Don't go into the principles . If readers want to know more about , Don't waste time on this post 2. The client uses Google Official Volley Access server , Specific understanding Volley Please stamp here 3. There are three kinds of this post ...

  2. Android general shell Complete works of

    One .[ What is? shell] Linux Systematic shell As the shell of the operating system , Provide users with an interface to use the operating system . It's a command language . Command interpreter and programming language .shell It's users and Linux Interface program between kernel , Such as ...

  3. MFC webbrowser Read the document's meta analysis

    IDispatch* pDisp = NULL; IDispatch* pDisp2 = NULL; IHTMLDocument2 *pHtmlDoc2 = NULL; IHTMLElementCol ...

  4. eclipse newspaper An error has occurred,See error log for more details. java.lang.NullPointerException error

    eclipse newspaper An error has occurred,See error log for more details. java.lang.NullPointerException error , terms of settlement : ...

  5. [ turn ] simulation HttpContext Realization ASP.NET MVC Unit test

    as everyone knows ASP.NET MVC One of the significant advantages of unit testing is that it is very convenient to implement unit testing , But it's often used in our testing process HttpContext, By default, the unit testing framework does not provide HttpContext The simulation of , This passage ...

  6. MySQL 5.7 for Windows Decompressed version MySQL Service failed to start

    MySQL 5.7 for Windows Decompressed version configuration installation basedi ...

  7. About uC/OS Simple learning ( turn )

    1. Microkernel And Linux The first difference is , It's a microkernel , The functions implemented by the kernel are very simple , It mainly includes : Some general functions , Such as TaskCreate(),OSMutexPend(),OSQPost() etc. . Interrupt handling function , ...

  8. Front end upload component - Plupload effect : Start interface . ------------- You can upload a single file on the web . ------------- You can upload multiple ...

  9. 《 The world of animals 》 Scissors, stone, paper HDU --- 6418

    Topic linking : emmm The information for this question comes from < The world of animals > This is a movie played by Li Yifeng .. The main idea is probability , But it will lead ...

  10. 004-Go iris receive post json data

    package main import( "" " ...