python学习日记5-异常,文件

2023-12-31  本文已影响0人  livein80

1.异常

+++++++++++++++++++++++++++++++
异常是程序运行中出现的错误或者遗漏的bug就叫异常。

1. 异常语句的使用:
try:
    #可能出现异常的代码块
    print(4/0)
except Exception as e:
    #Exception 所有异常的父类,捕获后存储在e中
    print('出现异常时执行',e,type(e))
else:
    #没有出现错误时执行
    print('没有出现错误时执行')
finally:
    #finally,无论是否出现异常,都执行
    print('无论是否出现异常,都执行')

2.文件

+++++++++++++++++++++++++++++++

正常的文件读取操作为:打开文件open(fileName),操作文件(读取或者写入)file_obj.read(),关闭文件file_obj.close()。

file_name = './1.txt'
#打开文件
file_obj=open(file_name)
print(file_obj)
#<_io.TextIOWrapper name='../1.txt' mode='r' encoding='UTF-8'>
#操作文件()
file_obj.read()
#关闭文件
file_obj.close()

如果文件忘记关闭的话,资源会被长期占有,会造成内存泄漏。所以,可以使用with...as... 的方式读取文件。with...as...结束后会自动关闭文件。

file_name = './1.txt'
# with...as.. 的方式读取文件。结束后可以自动关闭
try:
    with open(file_name,encoding='utf-8') as file_obj:
        content = file_obj.read()
        print(content)
except Exception as e:
    print(e,type(e))
    #文件不存在时 [Errno 2] No such file or directory: './1.txt' <class 'FileNotFoundError'>

read() 来读取文件时,他会直接将所有的文件都读取出来,如果要读取的文件较大,一次性读取到内存里来时,会导致性能下降,内存溢出等问题。所以 可以使用分段读取的方式。譬如:

file_name = './1.txt'
try:
    with open(file_name,encoding='utf-8') as file_obj:
        # content = file_obj.read()
        chunk = 100
        while True:
            #read(size) 可以设置一个每次读取的长度值。以实现分段读取的作用
            content = file_obj.read(chunk)
            # 退出循环
            if not content:
                # 内容读取完毕后 退出循环
                break
            print(content,end="|||")
except Exception as e:
    print(e,type(e))

分段读取的其他方式还有:
# file_obj.readline() # 每次读取一行
# file_obj.readlines() #按照行数,将内容存放在list中

def fn():
    with open(file_name, encoding='utf-8') as file_obj:
        while True:
            line = file_obj.readline()
            yield line

f = fn()
print(next(f),end='---------')
print(next(f),end='---------')

当然,也可以结合readline(),使用生成器的方法来解决这个问题。

上一篇下一篇

猜你喜欢

热点阅读