[Python from zero to one] 3. File operation of syntax basis, reading and writing of CSV file and object-oriented

Eastmount 2020-11-13 00:00:55
python zero file operation syntax

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 .

One . File operations

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 .

1. Open file

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 :

  • r: read-only , The file pointer will be placed at the beginning of the file
  • w: Just write , Open the file if it already exists , And edit from the beginning , The original content will be deleted ; If the file does not exist , Create a new file
  • a: Open a file for appending , If the file already exists , The file pointer will be placed at the end of the file ; If the file does not exist , Create a new file to write to
  • rb: Read only binaries , Generally used for non - text files such as pictures
  • wb: Just write binary files , Generally used for non - text files such as pictures
  • ab: Open a file in binary format for appending
  • w+: Open a file for reading and writing

open() The complete syntax of the function is as follows :

  • open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

 Insert picture description here

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 .

2. Read and write files

(1) Reading documents
Common file reading methods include :

  • read() The return value is a string containing the entire text content
  • readline() The return value is the string of the content of the next line of the file content
  • readlines() The return value is a list of the contents of the entire file , Each item in the list is a line of string

Examples are as follows :

infile = open("test.txt","r",encoding="utf8")
data = infile.read()
infile = open("test.txt","r",encoding="utf8")
list_data = infile.readlines()

The output result is shown in the figure below :

 Insert picture description here
 Insert picture description here

(2) Writing documents
Write data from computer memory to a file , Methods include :

  • write() Write a string containing text data or binary data set to a file
  • writelines() For list operations , Receive a string list parameter , And write the file
outfile1 = open('test.txt','a+',encoding="utf8")
str1 = '\nhello\n'
str2 = 'world\n'
outfile2 = open('test02.txt','w',encoding="utf8")
outfile2.writelines(['hello',' ','world'])
infile = open('test.txt','r',encoding="utf8")
data = infile.read()

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 .

 Insert picture description here

 Insert picture description here

3. Close file

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 .

# File operations 
except :
# exception handling 

Other methods include :

  • file.flush(): Refresh file internal buffer
  • file.next(): Return to the next line of the file
  • file.seek(offset[, whence]): Set the current location of the file
  • file.tell(): Return to the current location of the file
  • file.truncate([size]): Intercept file , The bytes intercepted pass through size Appoint

4. Loop through the file

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():
infile = open('test02.txt', 'r', encoding="utf8").read()
for line in infile:

Output results 《 In the Quiet Night 》 As shown in the figure below , contain TXT Files and output values .

 Insert picture description here

Two .CSV File operations

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 .

1.CSV The document says

The basic process is as follows :

  • Import CSV modular
  • Create a CSV File object
  • write in CSV file
  • Close file
# -*- 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(" Xiao Ming ")
del tlist[:] # Empty 
tlist.append(" Xiaohong ")

The output result is shown in the figure below :

 Insert picture description here

Be careful , There will be extra blank lines , We need to do something simple , Add parameters “newline=‘’” solve .

  • c = open(“test-01.csv”, “w”, encoding=“utf8”, newline=’’)

 Insert picture description here

2.CSV File read

The basic process is as follows :

  • Import CSV modular
  • Create a CSV File object
  • Read CSV file
  • Close file
# -*- coding: utf-8 -*-
import csv
c = open("test-01.csv", "r", encoding="utf8") # Reading documents 
reader = csv.reader(c)
for line in reader:

The output result is shown in the figure below :

 Insert picture description here

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 .

 Insert picture description here

3、 ... and . Object oriented fundamentals

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 :

  • encapsulation : Encapsulate objective things into abstract classes , The data and methods in a class let the class or object operate .
  • Inherit : After the subclass inherits the parent class , It can use all the functions of the parent class , There is no need to rewrite the original class , And it can extend the function .
  • polymorphic : A property or behavior defined in a class , After being inherited by a special class , It can have different data types or behave differently , Each class can express different semantics , The two methods of implementation are covering and overloading .

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 
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 .

 Insert picture description here

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 :

 Insert picture description here
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 .

Four . summary

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 .

 Insert picture description here

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 :


  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database