Python learning notes

Posted by henryhund on Sat, 05 Feb 2022 18:44:03 +0100

About design mode (II)

(it also includes the knowledge content of modules and packages)

Read the picture file and copy the file

with open('Picture name','rb') as f:   #b is binary
    with open('New file name','wb') as w:
        for line in f.readlines():
print('Picture copy complete')

pickle serialization and deserialization

 pickle.dump(obj,file) obj is the object to be serialized, and file refers to the stored file
pickle.load(file) reads data from file} and reversely serializes it into an object

import  pickle
with open(r"d:\data.dat","wb") as f:
     #Serialize objects into files
#Deserialize the obtained data into objects
import  pickle
with open(r"d:\data.dat","rb") as f:

Operation of CSV file

In CSV file:
Values have no type and all values are strings
You cannot specify the width or height of a cell. You cannot merge cells
Styles such as font color cannot be specified
No more sheets
Cannot embed image chart

#Reading and writing CSV files
import csv
with open("dd.csv","r") as f:    #dd is the file name
       a_csv = csv.reader(f)
       for  row in a_csv:       #Traverse the contents of the file
              print(row)             #read
with open("ee.csv","r") as f:     #ee is the file name
      b_csv = csv.writer(f)
      b_csv.writerow(["ID","full name","Age"])

     c = [["1002","dfg","19"],["1003","fhj","20"]]
     b_csv.writerows(c)            #write in

os and os Path module

The os module can help us directly operate the operating system. We can directly call the executable files and commands of the operating system,
Direct operation of files, directories, etc
os.system can help us call system commands directly
os.system calls the Notepad program of windows system

import os
os.system call windows In the system ping command
import os

 Is Ping [] Data with 32 bytes:
From Reply from: byte=32 time=35ms TTL=54
 From Reply from: byte=32 time=24ms TTL=54
 From Reply from: byte=32 time=26ms TTL=54
 From Reply from: byte=32 time=21ms TTL=54 of Ping statistical information :
    data packet: has been sent = 4,Received = 4,lose = 0 (0% lose),
Estimated round trip time(In Milliseconds ):
    minimum = 21ms,Longest = 35ms,average = 26ms

Methods of common operation files under OS module

remove(path)Delete the specified file
rename(str.dest)Rename a file or directory
stat(path) Returns all properties of the file
listdir(path)Returns the list of files and directories in the path directory
mkdir(path)Create directory
makedirs(path1/path2/path3/...)Create multi-level directory
madir(path) Delete directory
removedirs(path1/path2/path3/...)Delete multilevel directory
getcwd()Return current working directory: current work dir
chdir(path)Set path to the current working directory
walk() Traverse the directory tree
sepThe path separator used by the current operating system

os.path module

isabs(path)Determine whether the path is an absolute path
isdir(path) Determine whether the path is a directory
isfile(path)Determine whether the path is a file
exists(path)Judge whether the file in the specified path exists
getsize(filename)Returns the size of the file
abspath(path)Return absolute path
dirname(p) Returns the path of the directory
getatime(filename) Returns the last access time of the file
getmtime(filename)Returns the last modification time of the file
walk(top,func,arg)Traversing directories recursively
join(path,*paths)Connect multiple path s
split(path)  Split the path
splitext(path)Splits the extension of the file from the path
import  os
import  os.path         #from os import path
print(os.path.isabs("file name"))

path = os.path.abspath("")

walk() recursively traverses all files and directories

os.walk() method:
Returns a tuple of three elements, (dirpath,dirnames,filenames)
dirpath: the path to list the specified directory
dirnames: all folders in the directory
filenames: all files in the directory

import os
path = os.getcwd()
list_ifles = os.walk(path)
for dirpath,dirnames,filenames in list_files:
      for dir in dirnames:
       for file in filenames:
import os
all_files = []
path = os.getcwd()
list_ifles = os.walk(path)
for dirpath,dirnames,filenames in list_files:
      for dir in dirnames:
       for file in filenames:
#Print files for all subdirectories
for file in all_files:

shutil module (copy and compression)

import shutil
shutil.copytree("Copied file","New file")(New file (need not exist)
shutil.copytree("","",ignaore=shutil.ignore_patterns("*.txt","*.html"))    At this time, the new file can be the original one

#Compression and decompression
shuttil.make_archive("","","")     The second is a compressed format, such as zip
 The third is the compressed file
 The first is the compressed address

#Compression method when shutil is not used
z1=zipfile.ZipFile("Compressed address","w")
z1.write("Compressed file")

z2=zipfile.ZipFile("Files to be unzipped","r")
z2.extractall("Unzip to directory")

Module import

import module name
There are four general categories of modules:
1. Code written in Python (. py file)
2. c or c + + extensions that have been compiled as shared libraries or DLL s
3. Package a set of modules
4. A built-in module written in c and connected to the Python interpreter
from...import imports the members (functions or classes) in the module

Import of packages

1,import  a.aa.module_AA
When using, you must add a full name to reference, such as a.aa module_ AA. fun_ AA()
2,from a.aa import module_AA
When using, you can directly use the module name. For example: module_AA.fun_AA()
3,from a.aa.module_AA import fun_AA # direct import function
When using, you can directly use the function name, such as fun_AA()
1. In the syntax from package import item, item can be package, module, function, class and variable
2,import item1. Item 2 or other modules in this package must not have item 2 syntax

__ init__. Three core functions of Py:
1. As the identification of the package, it cannot be deleted
2. Used to implement fuzzy import
3. The essence of importing a package is execution__ file, which can be found in__ file to initialize this package.
And the need for uniform code execution

Topics: Python Back-end