Welcome to “Python From zero to one ”, Here I'm going to share an appointment 200 piece Python Series articles , Take everyone to study and play together , have a look Python This interesting world . All articles will be combined with cases 、 Code and author's experience , I really want to share my nearly ten years programming experience with you , I hope it will be of some help to you , There are also some shortcomings in the article .
Python The overall framework of the series includes basic grammar 10 piece 、 Web crawler 30 piece 、 Visual analysis 10 piece 、 machine learning 20 piece 、 Big data analysis 20 piece 、 Image recognition 30 piece 、 Artificial intelligence 40 piece 、Python Security 20 piece 、 Other skills 10 piece . Your attention 、 Praise and forward is the greatest support for xiuzhang , Knowledge is priceless, man has love , I hope we can all be happy on the road of life 、 Grow up together .
This paper refers to the author CSDN The article , Links are as follows :
meanwhile , The author's new “ Na Zhang AI Safe house ” Will focus on Python And security technology , Mainly share Web penetration 、 System security 、 Artificial intelligence 、 Big data analysis 、 Image recognition 、 Malicious code detection 、CVE Reappear 、 Threat intelligence analysis, etc . Although the author is a technical white , But it will ensure that every article will be carefully written , I hope these basic articles will help you , stay Python And on the road to safety, progress with you .
A collection of data stored on external media , Text file encoding methods include ASCII Format 、Unicode code 、UTF-8 code 、GBK Coding, etc . The operation flow of the file is “ Open file - Read and write files - Close file ” Trilogy .
Open file call open() Function implementation , The returned result is a file object , The function prototype is as follows :
<variable> = open(<name>, <mode>)
-<name> Indicates the name of the open file
-<mode> Indicates file open mode
among mode Common parameters include :
open() The complete syntax of the function is as follows :
Let's take a simple example :
infile = open("test.txt","r")
Be careful : Use open() Methods must ensure that the file object is closed , That is to call close() Method .
(1) Reading documents
Common file reading methods include :
Examples are as follows :
infile = open("test.txt","r",encoding="utf8")
data = infile.read()
print(data)
print("")
infile = open("test.txt","r",encoding="utf8")
list_data = infile.readlines()
print(list_data)
The output result is shown in the figure below :
(2) Writing documents
Write data from computer memory to a file , Methods include :
outfile1 = open('test.txt','a+',encoding="utf8")
str1 = '\nhello\n'
str2 = 'world\n'
outfile1.write(str1)
outfile1.write(str2)
outfile1.close()
outfile2 = open('test02.txt','w',encoding="utf8")
outfile2.writelines(['hello',' ','world'])
outfile2.close()
infile = open('test.txt','r',encoding="utf8")
data = infile.read()
print(data)
in the light of test.txt The file completes the append write operation , in the light of test02.txt The file is created and written , At the same time call write() and writelines() Different ways to write data .
After reading and writing the file , Be sure to remember to use close() Method to close the file . If you forget to use the closing statement , When the program crashes suddenly , The program does not continue to write , Even when the program normally completes the file writing operation , Because the file operation is not closed , The file may not contain written data . To be on the safe side , You need to close the file after using it , The reader is advised to use try-except-finally Exception capture statements , And in finally Clause to close the file .
try:
# File operations
except :
# exception handling
finally:
file.close()
Other methods include :
In data crawling or data analysis , File traversal is often involved , Usually used for Loop through the contents of the file , On the one hand, it can call read() Function read file loop output , On the other hand, you can call readlines() Function implementation . The comparison code of the two methods is as follows :
infile = open('test02.txt', 'r', encoding="utf8")
for line in infile.readlines():
print(line)
print(infile.close())
infile = open('test02.txt', 'r', encoding="utf8").read()
for line in infile:
print(line)
print(infile.close())
Output results 《 In the Quiet Night 》 As shown in the figure below , contain TXT Files and output values .
We are using Python When doing web crawler or data analysis , We usually meet CSV file , Be similar to Excel form . Then we add SCV Basic knowledge of file reading and writing .
CSV(Comma-Separated Values) Is a commonly used storage file , GNU sed , Values are separated by semicolons .Python Import CSV The expansion pack can be used , Including writing files and reading files .
The basic process is as follows :
# -*- coding: utf-8 -*-
import csv
c = open("test-01.csv", "w", encoding="utf8") # Writing documents
writer = csv.writer(c)
writer.writerow([' Serial number ',' full name ',' Age '])
tlist = []
tlist.append("1")
tlist.append(" Xiao Ming ")
tlist.append("10")
writer.writerow(tlist)
print(tlist,type(tlist))
del tlist[:] # Empty
tlist.append("2")
tlist.append(" Xiaohong ")
tlist.append("9")
writer.writerow(tlist)
print(tlist,type(tlist))
c.close()
The output result is shown in the figure below :
Be careful , There will be extra blank lines , We need to do something simple , Add parameters “newline=‘’” solve .
The basic process is as follows :
# -*- coding: utf-8 -*-
import csv
c = open("test-01.csv", "r", encoding="utf8") # Reading documents
reader = csv.reader(c)
for line in reader:
print(line[0],line[1],line[2])
c.close()
The output result is shown in the figure below :
In file operation, the coding problem is the most troublesome , especially Python2 When . But only the environment code is consistent , Note that correlation transformation can also effectively solve , and Python3 Read and write files clearly encoding The encoding mode can display normally . If it's a database 、 Webpage 、 Background language , The three coding methods need to be consistent , such as utf8 or gbk etc. , Solve the specific problems ! The following author will explain with reptile CSV Operation of file .
The traditional way of programming is process oriented , Execute from top to bottom according to business logic , Object oriented programming is another way of programming , This kind of programming needs to use “ class ” and “ object ” To achieve , Encapsulate the function , A way of programming closer to real life .
Object oriented is the object that regards objective things as properties and behaviors , By abstracting the common properties and behaviors of the same class of objects , Formative class , Through the inheritance and polymorphism of the class to achieve code reuse and so on . object (Object) It's a class (Class) An example of , If you compare an object to a house , Then the class is the design of the house , And define the properties and methods in the class .
The three basic characteristics of object-oriented are :
stay Python in , Class is a template , Templates can contain multiple functions , Functions to achieve some functions ; Objects are instances created from templates , Function in class can be executed through instance object . as follows :
# Create a class
class Class name :
# Create a function in a class ,self Special parameters , Don't omit
def Function name (self):
# Function implementation
# Create objects from classes obj
obj = Class name ()
Suppose you need to write a program to calculate the area and perimeter of a rectangle , The idea is to define two variables, length and width , Then define the method to calculate the area and perimeter in the class , Instantiate using . The code is as follows :
#-*- coding:utf-8 -*-
class Rect:
def __init__(self, length, width):
self.length = length;
self.width = width;
def detail(self):
print(self.length, self.width)
def showArea(self):
area = self.length * self.width
return area
def showCir(self):
cir = (self.length + self.width) * 2
return cir
# Instantiation
rect1 = Rect(4,5)
# Call function
rect1.detail()
area = rect1.showArea()
cir = rect1.showCir()
print(' area :', area)
print(' Perimeter :', cir)
The area of the output result is 20, The perimeter of 18. For object-oriented encapsulation , In fact, we use construction methods to encapsulate content into objects , And then through the object directly or self Indirect access to encapsulated content .
As a whole , Object oriented is to think and solve problems from the perspective of things themselves , If the above is implemented in the form of process oriented function , When multiple shapes appear , You need to define a method for each shape , Object oriented only needs to abstract the properties and methods of these shapes , In various shapes , More realistic .
Be careful : In order to make readers learn more concisely and quickly Python Data crawling 、 Data analysis 、 Image recognition and other knowledge , The code in this series rarely presents in the way that classes and objects are defined , It's a function or case that is implemented directly on demand , Write the corresponding code or function directly . This is not standard and unreasonable , In actual development or more standard code , It is recommended that you use the object-oriented method to program , But this series wants to tell you the principle through the simplest code , Then you can improve and exercise your abilities .
Object oriented in design patterns
Another example : In order to facilitate children to learn programming ,X The company has developed a set of Racing Car Simulator , With this simulator, every child can control a racing car in a simple language , for example right、left etc. . Please design a simple language , The syntax and class diagram of the language are given .
This is the problem that we connect with life in actual programming , It involves knowledge of design patterns , The method I used is “ Naming patterns ” Realized , The client is the definition Children and Car, The requester is Children Emitted Right、Left、Up、Down command , The recipient is Car perform Move(), Abstract commands are abstract interfaces up and down , The specific order is Car Up and down, around . The class diagram I made is as follows :
In this case , We use object-oriented ideas , Think and solve problems from the perspective of things themselves , Instead of the formal implementation of process oriented functions . If there's another air and land vehicle , It can not only move up and down, left and right , And fly , The traditional method also needs to write four more ways to move up and down, left and right , And object oriented inheritance Car, Add a new method of flight ( Without direction ), That's the benefit of object orientation .
Again , Through this example, I don't want to prove whether the command pattern or class diagram drawn is correct , What I want to explain is that we learn object-oriented knowledge mainly to solve problems in real life , Make it more efficient to solve problems and optimize code . meanwhile , The object-oriented idea should adapt to the change of requirements , Solve the actual needs of users , Try to consider the changes in the design , It's going to involve abstraction 、 Packaging changes ( a key )、 Design patterns, etc .
in any case , The author hopes that this article can popularize some Python knowledge , I hope you can write code with me , Progress together . If the article can give you some trivial ideas and help with your research or project , It's even more gratifying . The author's biggest expectation is some stories in the article 、 word 、 Code or cases can help you , To those who struggle .
I appreciate :
Last , Thank you for your attention “ Na Zhang's home ” official account , thank CSDN So many years of company , Will always insist on sharing , I hope your article can accompany me to grow up , I also hope to keep moving forward on the road of technology . If the article is helpful to you 、 Have an insight , It's the best reward for me , Let's see and cherish !2020 year 8 month 18 The official account established by Japan , Thank you again for your attention , Please help to promote it “ Na Zhang's home ”, ha-ha ~ Newly arrived , Please give me more advice .
regret , Let's understand perfection .
Pass away , Let's move on .
Her posture in the night is so beautiful .
(By: Na Zhang's home Eastmount 2020-09-22 Night in Wuhan https://blog.csdn.net/Eastmount )
The references are as follows :