File reading and writing supplement (reading large files + writing files + reading and writing binary files + super() 2020-12-4

1. The open() function opens a file

To open a file with the open() function, the file can be divided into two types:

  • Plain text file: A text file written in utf-8
  • Binary files: picture, audio, video. After the
    text is opened, the English plain text can be read directly, but the Chinese plain text needs encoding='utf-8'
file_name='Demo02.txt'
try:
    with open(file_name,encoding='utf-8') as file_obj:
        content = file_obj.read()
        print(content)
except FileNotFoundError:
    print(f'文件{file_name不存在}')

result

Hello World!!!
白日依山尽
黄河入海流
欲穷千里目
更上一层楼

The open() function opens the file in plain text mode by default.
read() will read all the contents of the file. If the file is large, it will cause insufficient memory space. Therefore, the read() function is generally not used directly.

1.1 How to read large files

The read() function can pass in numeric parameters, which represent the number of characters printed each time. The default parameter is -1. For example, I can pass in 6 as the parameter in this example, because each line of five characters plus a newline character is exactly 6 characters. But the last line does not need to wrap, there are five characters, but 6 is still passed in, and no error is reported. When the number of characters is less than the parameter passed in, all characters are printed.

file_name='Demo02.txt'
try:
    with open(file_name,encoding='utf-8') as file_obj:
        content = file_obj.read(6)
        print(content)
except FileNotFoundError:
    print(f'文件{file_name不存在}')

result

白日依山尽

What if I add another line of printing code?

file_name='Demo02.txt'
try:
    with open(file_name,encoding='utf-8') as file_obj:
        content = file_obj.read(6)
        content = file_obj.read(6)
        print(content)
except FileNotFoundError:
    print(f'文件{file_name不存在}')

result,

黄河入海流

We found that the previous sentence was overwritten, instead of printing out two sentences. In this way, we can write a loop to control the printing and print out the results, and instead of reading them all at once with the read() function, we can read them step by step.

file_name='Demo02.txt'
try:
    with open(file_name,encoding='utf-8') as file_obj:
        chunk = 100
        while True:
            content = file_obj.read(chunk)
            if not content:
                break
            print(content)
except FileNotFoundError:
    print(f'文件{file_name不存在}')

result

白日依山尽
黄河入海流
欲穷千里目
更上一层楼

This is a method of reading block by block in order to avoid memory benefits.

1.2 File writing

The open() function opens a read-only file by default, and cannot write content. If you want to write, when you open it, you must pass in the parameter'w' and write. If there is already content in the file, the content will be overwritten by the newly written content, if there is no content, the content will be written.

file_name='Demo02.txt'
with open(file_name,'w',encoding='utf-8') as file_obj:
	r=file_obj.write('今天是最后一节课啦啦啦')
	print(r)
	file_obj.close()  # 关闭已经打开的文件
with open(file_name,'r',encoding='utf-8') as file_obj:
	content = file_obj.read(100)
	print(content)

result

11
今天是最后一节课啦啦啦

We see that the content in the text Demo02.txt has been covered by the new content. Note that the content passed in the write() function can only be a string, not a number or other. And this function has a return value, which returns the number of characters written.
If you don't want the previous content to be overwritten, you need to pass in the parameter'a' when opening it , which means append .

file_name='Demo02.txt'
with open(file_name,'a',encoding='utf-8') as file_obj:
	file_obj.write('这是追加的内容')
	file_obj.close()  # 关闭已经打开的文件
with open(file_name,'r',encoding='utf-8') as file_obj:
	content = file_obj.read(100)
	print(content)

result

今天是最后一节课这是追加的内容

There is also a parameter x, which is passed in when the open() function is used. If the opened file exists, an error will be reported, and it will be created if it does not exist.

file_name='Demo04.txt'
with open(file_name,'a',encoding='utf-8') as file_obj:
	file_obj.write('这是新键Demo04文件里写入的内容。')
	file_obj.close()  # 关闭已经打开的文件
with open(file_name,'r',encoding='utf-8') as file_obj:
	content = file_obj.read(100)
	print(content)

result
Insert picture description here

2. Reading and writing of binary files

Let's do a project to understand the reading and writing of binary files. Compared with plain text files, binary files refer to files such as pictures, audios, and videos.
Example: Read a music file "Break the dividing wall.mp3", then write it into a file, and name it "New_break the dividing wall.mp3".
Code:

file_name= r'C:\Users\MI\OneDrive\桌面\Break the dividing wall.MP3' # 我事先在桌面放了一个音乐文件
with open(file_name,'rb') as file_obj: # 'rb'代表以二进制文件打开,没有传入这个参数默认的参数是't'这个参数可以不写,即纯文本的意思
	#new_name = 'New_break dividing wall.mp3'  如果这样建,后面open()函数直接打开,就会在这个程序模块同一个文件夹里生成文件,不方便查找。所我把老师的代码改了。如下:
	with open(r'C:\Users\MI\OneDrive\桌面\New_break dividing wall.mp3','wb') as new_obj:
		chunk = 100 * 1024
		while True:
			content = file_obj.read(chunk)
			if not content:
				break
			new_obj.write(content)

As a result, this result is not easy to display. As a result, a new file "New_break dividing wall.mp3" appeared on my desktop and opened for listening, which was the same as the previous content. In fact, it is also possible to replace it with video pictures.

3. super() (extended)

This is a knowledge point related to inheritance. If the subclass also needs to define the init method, it will conflict with the init method of the parent class. To solve this problem, Python specifically defines a super(). Regarding its usage, we will show it with an example.
example:

class Person:
	def __init__(self):
		self.name='张三'
		self.age=18
	def run(self):
		print(f'{self.name}在跑步。')
	def eat(self):
		print(f'{self.name}在吃饭。')
class Students(Person):
	pass
class Teachers(Person):
	pass
s=Students()
s.run()
s.eat()

result

张三在跑步。
张三在吃饭。

Now I want to define an init method in the subclass, of course it is possible:

class Person:
	def __init__(self):
		self.name='张三'
		self.age=18
	def run(self):
		print(f'{self.name}在跑步。')
	def eat(self):
		print(f'{self.name}在吃饭。')
class Students(Person):
	def __init__(self):
		print('我是Students中的init方法')

class Teachers(Person):
	pass
s=Students()

We found that there is no problem when creating an instance:

我是Students中的init方法

But an error was reported when the method was called.

class Person:
	def __init__(self):
		self.name='张三'
		self.age=18
	def run(self):
		print(f'{self.name}在跑步。')
	def eat(self):
		print(f'{self.name}在吃饭。')
class Students(Person):
	def __init__(self):
		print('我是Students中的init方法')
	pass
class Teachers(Person):
	pass
s=Students()
s.run()

result

我是Students中的init方法
Traceback (most recent call last):
  File "D:/work/基础/Day17/Demo01.py", line 59, in <module>
    s.run()
  File "D:/work/基础/Day17/Demo01.py", line 49, in run
    print(f'{self.name}在跑步。')
AttributeError: 'Students' object has no attribute 'name'

Saying that the Students object does not have the name attribute, it means that it failed to inherit the parent class. The init method of the subclass and the init method of the parent class are executed at the beginning, of course, the latter overrides the former, and the latter does not define the name attribute. Let's add a line of code to verify:

class Person:
	def __init__(self):
		self.name='张三'
		self.age=18
		print('我是Person中的init方法')
	def run(self):
		print(f'{self.name}在跑步。')
	def eat(self):
		print(f'{self.name}在吃饭。')
class Students(Person):
	def __init__(self):
		print('我是Students中的init方法')
	pass
class Teachers(Person):
	pass
s=Students()

result

我是Students中的init方法

We can see that only the statements in the subclass are printed out, again confirming that the init method in the subclass overwrites the init method in the previous parent class. If we want to define our own init method in the subclass, or even we can customize the properties and methods that belong to the subclass, we need to use the super() class to solve the problem. Let’s not say much, just look at the code:

class Person:
	def __init__(self):
		self.name='张三'
		self.age=18
		print('我是Person中的init方法')
	def run(self):
		print(f'{self.name}在跑步。')
	def eat(self):
		print(f'{self.name}在吃饭。')
class Students(Person):
	def __init__(self):
		print('我是Students中的init方法')
		super().__init__()  # 添加的代码
class Teachers(Person):
	pass
s=Students()
s.run()
s.eat()

result

我是Students中的init方法
我是Person中的init方法
张三在跑步。
张三在吃饭。

We see that when added

super().__init__()

After this line of code, all problems are solved. The subclass successfully inherits the properties of the parent class, and the statement in the parent class is also printed out, not being covered by the init method of the subsequent subclass. This line of code is equivalent to calling the init method of the parent class. When we call the run() and eat() methods in the following examples, both of them use the attributes defined in the parent class init method, so the parent class’s init method must be called later. Now, we try to define our own properties in the subclass.

class Person:
	def __init__(self,name,age):
		self.name=name
		self.age=age
		print('我是Person中的init方法')
	def run(self):
		print(f'{self.name}在跑步。')
	def eat(self):
		print(f'{self.name}在吃饭。')
class Students(Person):
	def __init__(self,name,age):
		print('我是Students中的init方法')
		super().__init__(name,age)
class Teachers(Person):
	pass
s=Students('张三','18')
s.run()
s.eat()

result

我是Students中的init方法
我是Person中的init方法
张三在跑步。
张三在吃饭。

Screenshot

Insert picture description here
Below we define the attributes of a class in the student class:

class Person:
	def __init__(self,name,age):
		self.name=name
		self.age=age
		print('我是Person中的init方法')
	def run(self):
		print(f'{self.name}在跑步。')
	def eat(self):
		print(f'{self.name}在吃饭。')
class Students(Person):
	def __init__(self,name,age,banji):
		print('我是Students中的init方法')
		super().__init__(name,age)
		self.banji=banji
class Teachers(Person):
	pass
s=Students('张三','18')
s.run()
s.eat()
print(s.banji)

result

我是Students中的init方法
我是Person中的init方法
张三在跑步。
张三在吃饭。
Python基础班

We see that everything is running, there is no problem. To summarize:
if the subclass inherits the parent class, the subclass must define an init method, call the init method of the parent class with super(), and write the properties in the parent class regardless of whether it is used or not. The unique attributes of the subclass can be written in the subclass's own init method.
Screenshot
Insert picture description here

4. Homework

4.1 Blogging and sorting out knowledge points

4.2 Classroom purchase at least three times

Guess you like

Origin blog.csdn.net/m0_46738467/article/details/110670474