Exceptions and files

abnormal

Abnormal propagation

  • In the process of running the program, some errors cannot be avoided. These errors are called exceptions. The code after the exception will not be executed to prevent the propagation of the exception.
  • Handle exception try statement
    try:
      代码块(可能出现错误的语句)
    except:
      代码块(出现错误之后要执行的语句)
    else:
      代码块(没有出现错误我要执行的语句)
print('python')
try:
    print(b)
except:
    print('出错了')
else:
    print('程序正常执行没有错误')
print('jkjkjkl')
python
出错了
jkjkjkl

Abnormal propagation

  • When an exception occurs in the function, if the exception is handled, the exception will not continue to propagate, if it is not handled in the function, the exception will continue to propagate to the function call
def fn():
    print('我是fn')
    print(100/0)# division by zero
#fn()# division by zero

The exception propagated from the inside of the function to the outside of the function

def fn1():
    print('我是fn1')
    print(100/0)# division by zero
def fn2():
    print('我是fn2')
    fn1()
def fn3():
    print('我是fn3')
    fn2()
# fn3()# division by zero
print(ZeroDivisionError)
<class 'ZeroDivisionError'>

Until it is passed to the global scope, if there is still no processing, the program will terminate and display the exception information. When the program is abnormal during operation, all the exception information will be saved to a special exception object, and when the exception is propagated, the actual The above is the exception object thrown to the caller

Exception object

  • How to get the abnormal object?
print('异常出现前')
try:
    # print(b)
    print(100/0)
except NameError:
    # 如果在except后面不加任何的内容,此时他会捕获所有的异常
    # 如果在except后面跟着一个异常类型,那么他只会捕获该类型的异常
    print('出现了NameError错误了')
print('异常出现后')
print('出现异常前')
try:
    print(b)
except Exception as e:
    print('.......',e,type(e))
finally:
    print('无论是否出现异常,都会执行')
print('出现异常后')
出现异常前
....... name 'b' is not defined <class 'NameError'>
无论是否出现异常,都会执行
出现异常后

All exceptions have the same parent class: Exception
try statement at this time:

try:
    代码块(可能出现的错误的语句)
except 异常类型 as 异常名:
    代码块(出现错误以后我的处理方式)
except 异常类型 as 异常名:
    代码块(出现错误以后我的处理方式)
except 异常类型 as 异常名:
    代码块(出现错误以后我的处理方式)
except 异常类型 as 异常名:
    代码块(出现错误以后我的处理方式)
.........
else:
    代码块(没有出错我要执行的语句)
finally:
    代码块(不管代码块是否异常,该代码块都会执行)

File

The file is also called (I/O) (Input/Output)

  • Steps to manipulate files:
    1. Open the file
    2. Read and write the
    file 3. Close the file

File opening

  • Through the python program to add, delete, modify and check various files in the computer
  • Open the file through the open() function.
    Syntax:

open(file,mode ='r',buffering = None,encoding = None,errors = None,newline = None,closefd = True)
parameter file The name (path) of the file to be opened The
open() function has a return value, What is returned is an object, what is returned is the currently opened file

If the file to be opened is in the same directory as the py file

file_name = 'demo.txt'
file_obj = open(file_name)
print(file_obj)
<_io.TextIOWrapper name='demo.txt' mode='r' encoding='cp936'>

If the file to be opened and the py file are not in the same directory

file_name = r'C:\Users\张浩哲\Desktop\demo.txt'
file_obj = open(file_name)
print(file_obj)
<_io.TextIOWrapper name='C:\\Users\\张浩哲\\Desktop\\demo.txt' mode='r' encoding='cp936'>

File closing

  • When we get the file object, all operations are performed through the file object
  • Read the content of the file, read the content of the file through the read() function, it will save the read content into a string
  • Close the file: file_obj.close()
file_name = 'demo.txt'
file_obj = open(file_name)
content = file_obj.read()
print(content)
file_obj.close()
dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccccccccccccccccccccccccccccccccc
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll

with...as statement: can avoid forgetting to close the file because of too much code

file_name = 'demo.txt'
with open(file_name) as file_obj:
    # 在with语句中直接使用file_obj来操作文件
    print(file_obj.read())
dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccccccccccccccccccccccccccccccccc
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll
file_name = 'python'
try:
    with open(file_name) as file_obj:
        print(file_obj.read())
except FileNotFoundError:
    print(f'{file_name}文件不存在')

File reading

Let’s first look at a phenomenon

file_name = 'demo.txt'
try:
    with open(file_name) as file_obj:
        content = file_obj.read()
        print(content)
except FileNotFoundError:
    print(f'{file_name}文件不存在')
dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccccccccccccccccccccccccccccccccc
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll

If the file to be read is English letters, it can be read smoothly, but what about Chinese?

file_name = 'demo2.txt'
try:
    with open(file_name) as file_obj:
        content = file_obj.read()
        print(content)
except FileNotFoundError:
    print(f'{file_name}文件不存在')

An error will be reported.
This is because open() is called to open a file. The opened file can be divided into two types:

  • One is plain text (a text file written in utf-8)
  • One is the binary file (picture audio video PPT)
    how to solve this error?
    You can specify the encoding of a file after file_name, such as utf-8 utf-16 utf-32 gbk, etc. After
    solving this problem, we found that if the characters occupy too much when reading a text file, then the memory occupied is also There are many. At this time, we don't want to be able to read all the characters at a time. This is a hidden danger, so how to solve this problem?
    At this time, we will introduce a function read()
  • read() can accept a size as a parameter to pass
  • The default value is -1 will read all characters, this parameter is used to specify the number of characters to read
  • You can specify a value for size, so that read() will read the specified number of characters, and each time it is read, it will continue to read from the last read position. If the number of remaining characters is less than size, Then read the remaining content at once
file_name = 'demo2.txt'
try:
    with open(file_name,encoding = 'gbk') as file_obj:
        # help(file_obj.read)
        content = file_obj.read(6)
        print(content)
        print(len(content))
except FileNotFoundError:
    print(f'{file_name}文件不存在')
靠靠靠靠靠靠
6

In this way, hidden dangers are avoided.

file_name = 'demo.txt'
try:
    with open(file_name,encoding = 'utf-8') as file_obj:
        # 定义一个变量来保存结果
        file_content = ''
        # 定义一个变量来指定读取的大小
        chunk = 5
        while True:
            content = file_obj.read(chunk)
            # 没有内容退出循环
            if not content:
                break
            file_content += content
except FileNotFoundError:
    print(f'{file_name}文件不存在')
print(file_content)
dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccccccccccccccccccccccccccccccccc
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll
file_name = 'demo.txt'
with open(file_name,encoding = 'utf-8') as file_obj:
    # print(file_obj.read())
    # readline()该方法可以读取一行内容
    print(file_obj.readline(),end = '')
    print(file_obj.readline(),end = '')
    print(file_obj.readline(),end = '')
    # readlines()该方法用于一行一行的读取,他将读取的内容全部封装到一个列表当中进行返回
    r = file_obj.readlines()
    print(r)
    print(len(r))
    print(r[0])
dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccccccccccccccccccccccccccccccccc
[',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\n', 'llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll']
2
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

File writing

  • Write content to the file through write(). If the operation is a text file, write() needs to pass a string, and specify the type of operation when operating the file
  • w means writable. When using w to write a file, a file will be created if the text does not exist, and the original file will be overwritten if it exists
file_name = 'demo.txt'
with open(file_name,'w',encoding = 'utf-8') as file_obj:
    file_obj.write('nice to meet you')
nice to meet you

How to append to the file? a means append

file_name = 'demo.txt'
with open(file_name,'a',encoding = 'utf-8') as file_obj:
    file_obj.write('nice to meet you\n')
    file_obj.write('dfadfadgg\n')
    file_obj.write('13243544\n')
    file_obj.write('gsdfgsdfgsf\n')
    file_obj.write('hkkkkl;l;iulouk\n')
nice to meet younice to meet you
dfadfadgg
13243544
gsdfgsdfgsf
hkkkkl;l;iulouk

Manipulate binary files

b means operating binary file
rb means reading binary file
wb means writing binary file
ab means appending binary file

file_name = r'C:\Users\张浩哲\Desktop\果汁音乐-只听最动听的歌.mp3'
with open(file_name,'rb') as file_obj:
    # print(file_obj.read(100))
    # 定义一个新的文件
    new_name = 'abc.mp3'
    with open(new_name,'wb') as new_obj:
        # 定义一个读取的大小
        chunk = 1024 * 100
        while True:
            content = file_obj.read(chunk)
            if not content:
                break
            new_obj.write(content)

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45671732/article/details/108938057
Recommended