Exceptions and files

1. Introduction to the exception

  • Brief introduction of the exception:
  • Some errors may occur during the running of the program. For example: using a non-existent index, adding two different types of data. . . These errors are called exceptions.
  • Handling exceptions:
  • An exception occurs when the program is running, and the purpose is not to make our program directly terminate! Python hopes that when an exception occurs, we can write code to handle the exception.
    Demo 1:
import requests
print('python')
# try代码的意思时尝试执行以下代码,如果代码不会出错,就直接执行try内部的代码;如果出错,则执行except内部的代码。
try:
    response = requests.get('www.baidu.com')
    print(response)
except:
    print('代码出错才会执行本语句!')
else:
    print('代码没有出错')
print('pycharm')

Print output result:

python
代码出错才会执行本语句!
pycharm

Demo 2:

import requests
print('python')
# try代码的意思时尝试执行以下代码,如果代码不会出错,就直接执行try内部的代码;如果出错,则执行except内部的代码。
try:

    print(111)
except:
    print('代码出错才会执行本语句!')
else:
    print('代码没有出错')
print('pycharm')

Print output result:

python
111
代码没有出错
pycharm
  • The syntax for handling exceptions:
try:
    代码块(可能出错的代码块):出错了就不执行,没有错就执行
except:
    代码块(出错了就执行的语句,没有出错就不执行)
else:
    代码(没有出错就执行,出错了就不执行)

Second, the spread of abnormalities

  • Transmission of anomalies:
  • 1. When an exception occurs in a function, if the exception is handled in the function, the exception will not be propagated. If the exception is not handled in the function, the exception will continue to propagate through function calls. If the function calling place handles the exception, it will not = propagate the exception, if it is not handled, it will continue to propagate to the calling place. Knowing that it is propagated to the global scope (main module), if there is still no processing, the program terminates and displays an exception message.
  • 2. When an exception occurs during program operation, all exception information will be saved in an exception object. When the exception is propagated, the exception object is actually thrown to the caller.
    Demo 1:
def fn():
    print('我是fn')
    try:
        a = 1 / 0
    except:
        print('代码出错了')

fn()

Print output result:
I am
wrong with fn code

Demo 2:

def fn():
    print('我是FN')
    a = 1 / 0

try:
    fn()
except:
    print('代码出错运行此行')

Print output result:
I am FN
code error run this line

Demo 3:

def fn():
    print('我是fn')
    a = 1 / 0


def fn1():
    print('我是fn1')
    fn()


def fn2():
    print('我是fn2')
    fn1()


def fn3():
    print('我是fn3')
    fn2()


fn3()

Print output result:

Traceback (most recent call last):
  File "D:\PycharmProjects\wangjiaxin\Python-Cheney老师基础讲解\第十五讲\2--异常的传播.py", line 47, in <module>
    fn3()
  File "D:\PycharmProjects\wangjiaxin\Python-Cheney老师基础讲解\第十五讲\2--异常的传播.py", line 44, in fn3
    fn2()
  File "D:\PycharmProjects\wangjiaxin\Python-Cheney老师基础讲解\第十五讲\2--异常的传播.py", line 39, in fn2
    fn1()
  File "D:\PycharmProjects\wangjiaxin\Python-Cheney老师基础讲解\第十五讲\2--异常的传播.py", line 34, in fn1
    fn()
  File "D:\PycharmProjects\wangjiaxin\Python-Cheney老师基础讲解\第十五讲\2--异常的传播.py", line 29, in fn
    a = 1 / 0
ZeroDivisionError: division by zero
我是fn3
我是fn2
我是fn1
我是fn

Conclusion: When there is an error in a function similar to the inheritance relationship, the subsequent functions will report an error.

Three, abnormal objects

  • ZeroDivisionError catches the division by zero error exception.
  • NameError catches undeclared initialized variable exception
  • Exception catches all exceptions.
    Demo 1:
print('异常出现之前')
try:
   # print(response)
   a = 1 / 0
except ZeroDivisionError:
    print('代码出错了')
print('异常出现之后')

Print output result:

异常出现之前
代码出错了
异常出现之后

Summary:
ZeroDivisionError means that the division by zero error exception can be caught.
ZeroDivisionError will only catch the exception of ZeroDivisionError, and will not catch other exceptions.

Demo 2:

print('异常出现之前')
try:
   print(response)
   # a = 1 / 0
except NameError:
    print('代码出错了')
print('异常出现之后')

Print output result:

异常出现之前
代码出错了
异常出现之后

Summary:
NameError represents an exception that can catch undeclared initialized variables.
NameError will only catch the exception of NameError, and will not catch other exceptions.

Demo 3:

# print('异常出现之前')
# try:
#    print(response)
#    a = 1 / 0
# except ZeroDivisionError:
#     print('ZeroDivisionError异常')
# except NameError:
#     print('NameErrory异常')
# print('异常出现之后')

Print output result:

异常出现之前
NameErrory异常
异常出现之后

Summary:
What kind of exception appears first, and execute what exception to catch. Subsequent exceptions will no longer be caught.

Demo 4:

print('异常出现之前')
try:
   print(response)
   a = 1 / 0
   print(1 + 'a')
except Exception as e:
    print('类型错误', e, type(e))
print('异常出现之后')

Print output result:

异常出现之前
类型错误 name 'response' is not defined <class 'NameError'>
异常出现之后
  • grammar:
try:
    代码块(可能出错的代码):出错了就不执行,没有错就执行。
except:
    代码块(出错了就执行的语句,没出错就不执行)
except Exception as e:
    代码块(出现异常我们的处理方式)
finally:
    代码块(是否有异常,都会执行)

Note : at least one of except and finally

Fourth, open the file

  • File opening:
  • File (file) through the Python program to add, delete, modify and check various files in the computer. File is also called I/O (input/output)
  • File operation:
  • 1. Open the file
  • 2. Perform various operations on the file (read, write, and then save)
  • 3. Close the file
  • The file will have a return value. Return an object, which represents the current file.
    Demo 1:
    Create a file demo in the target directory
file_name = 'demo'
response = open(file_name)
print(response)

Print output result:
<_io.TextIOWrapper name='demo' mode='r' encoding='UTF-8'>

Demo 2: Windows10 absolute path

file_name = 'D:\PycharmProjects\wangjiaxin\Python-Cheney老师基础讲解\第十四将\demo'
response = open(file_name)
print(response)

D:\PycharmProjects\wangjiaxin\Python-Cheney teacher basic explanation\fourteenth general\demo-this is the absolute path.

Demo 3: macos pairing path

file_name = '/Volumes/苹果微软公共盘/PycharmProjects/wangjiaxin/Python-Cheney老师基础讲解/第十四将/demo'
response = open(file_name)
print(response)

/Volumes/Apple Microsoft Public Disk/PycharmProjects/wangjiaxin/Basic explanation of Python-Cheney teacher/Fourteenth General/demo—This is the absolute path.

Demo 4: relative path

file_name = '..\第十四讲\demo'
response = open
print(response)

Print output result:

Five, close the file

Demo 1: Normal mode

  • close () method to close the file
file_name = 'demo'
resp = open(file_name)

content = resp.read()
print(content)
# 关闭文件
resp.close()
print(resp.read())

Print output result:

/Volumes/苹果微软公共盘/PycharmProjects/venv/bin/python /Volumes/苹果微软公共盘/PycharmProjects/wangjiaxin/Python-Cheney老师基础讲解/第十五讲/5--关闭文件.py
12580
Traceback (most recent call last):
  File "/Volumes/苹果微软公共盘/PycharmProjects/wangjiaxin/Python-Cheney老师基础讲解/第十五讲/5--关闭文件.py", line 9, in <module>
    print(resp.read())
ValueError: I/O operation on closed file.

Demo 2: Upgrade mode

  • with. . The as statement does not need to write close() to close. With automatic shutdown.
file_name = 'demo'
with open(file_name) as resp:
    content = resp.read()
    print(content)

respose = resp.read()
print(respose)

Print output result:

/Volumes/苹果微软公共盘/PycharmProjects/venv/bin/python /Volumes/苹果微软公共盘/PycharmProjects/wangjiaxin/Python-Cheney老师基础讲解/第十五讲/5--关闭文件.py
Traceback (most recent call last):
  File "/Volumes/苹果微软公共盘/PycharmProjects/wangjiaxin/Python-Cheney老师基础讲解/第十五讲/5--关闭文件.py", line 19, in <module>
    respose = resp.read()
ValueError: I/O operation on closed file.
12580

Demo 3: Advanced mode

file_name = 'demo1'
try:
    with open(file_name) as resp:
        content = resp.read()
        print(content)
except Exception as e:
    print('没有这个文件', type(e))

Print output result:

/Volumes/苹果微软公共盘/PycharmProjects/venv/bin/python /Volumes/苹果微软公共盘/PycharmProjects/wangjiaxin/Python-Cheney老师基础讲解/第十五讲/5--关闭文件.py
白日依山尽
黄河入海流
欲穷千里目
更上一层楼

Insert picture description here

Six, read the file

  • Read the file:
  • Read the contents of the file through read()
  • Call open() to open a file, the file can be divided into 2 types
    • A plain text file (a file written using utf-8 encoding)
    • A binary file (picture mp3 video...)
    • When open() opens a file, it is opened as a text file by default. The default encoding of open() is None. So specify the encoding when processing text files
  • Reading of larger files:
  • When reading the contents of a file through read(), all contents in the file will be read out. If the file to be read is relatively large. The file will be loaded into the content all at once. Easily lead to memory leaks. So for larger files. Don't call read() directly.
  • read() can receive a size as a parameter. This parameter is used to specify the number of characters to be read. The default value is -1.-1 which means to read all the contents.
  • Each read will start from the last read position. If the number of characters is less than size. All will be read. If the last file is read. It will return an empty string.
  • readline() This method is used to read a line.
  • readline() This method is used to read the content line by line. It will encapsulate the read content into a list and return it at once.
    Demo 1:
    Insert picture description here
file_name = 'demo1'
try:
	with open(file_name) as resp:
		content = resp.read()
		print(content)
except FileExistsError:
	print(f'{file_name}文件不存在')

The printout:
sun mountains
Yellow River flows into the sea
for a grander sight
to the next level

  • File types that open can open:

    • 1. Plain text (text file written using utf-8)
    • 2. Other binary files (pictures, videos, music)
  • Other file reading methods: readline() This method is used to read the content line by line. It will encapsulate the read content into a list at one time and return it.

Demo:

file_name = 'demo1'

try:
    with open(file_name) as resp:
        for i in range(6):
            content = resp.readline()
            print(content,end='')
except FileExistsError:
    print(f'{file_name}文件不存在')

Seven, file writing

  • write() to write content to the file
    • This method can write content to the file multiple times.
    • After the writing is complete, the method will return the number of written characters
  • When you use the open() function to open a file, you must specify the operations (read, write, append) to open the file. If you do not specify the operation type, the default is to read the file, and you cannot write to the file when reading the file.
    • r means read only
    • w means writable. When writing a file with w, a file will be created if the file does not exist. If the file exists, the content of the original file will be overwritten.
    • a means append.
      Demo 1:
file_name = 'demo1'

# 'w'是覆盖式写入的意思
try:
    with open(file_name, 'w', encoding='utf-8') as resp:
        content = resp.write('123\n')
        content = resp.write('456\n')
        content = resp.write('789\n')
except:
    print('出错了')

Print output result:

/Volumes/苹果微软公共盘/PycharmProjects/venv/bin/python /Volumes/苹果微软公共盘/PycharmProjects/wangjiaxin/Python-Cheney老师基础讲解/第十五讲/9--文件的写入.py

Process finished with exit code 0

Demo 2:

file_name = 'demo1'

# 'a'是追加的意思
try:
    with open(file_name, 'a', encoding='utf-8') as resp:
        content = resp.write('123\n')
        content = resp.write('456\n')
        content = resp.write('789\n')
except:
    print('出错了')

Print output result:

123
456
789
123
456
789

Insert picture description here

Eight, binary files

  • When reading a text file, size is in characters. When reading a binary file, size is in bytes
  • We use wb to write binary files
    Demo:
file_name = r'/Users/wangjiaxin/Desktop/111.ncm'

# rb时读写二进制文件的意思
try:
    with open(file_name, 'rb') as resp:
        new_file = '124.mp3'
        # print(resp.read())
        # wb写入二进制文件

        with open(new_file, 'wb') as f:
            while True:
                content = resp.read(1024*800)
                if not content:
                    break
                f.write(content)



except:
    print('出错了')

Because of the format conversion problem, this procedure has no results.

Guess you like

Origin blog.csdn.net/Rhymeplot__JDQS/article/details/109299195