9月21日课后笔记

9月21日课后笔记

异常快速入门

# 异常
# 在程序运行的过程中,不可避免的会出现一些错误。比如 使用了不存在的索引,if 引用了没有赋值的变量..:
# 这些错误我们称之为异常
# 程序一旦出现异常,会导致程序立即终止,异常后面的代码都不会执行
# print(abc)
# NameError: name 'abc' is not defined

# print('hello')
# print(6/0)
# ZeroDivisionError: division by zero
# print('java')

# 处理异常
# 程序出现异常,目的并不是让我们的程序终止
# 而是希望我们在出现异常的时候,能够编写相应的代码来对异常进行处理
# try语句
# try:
#     代码块(可能出现错误的语句)
# except:
#     代码块(出现错误以后的处理方式)
# else:
#     代码块(没有出现错误的语句)

# print('hello')
# try:
#     print(6/2)
# except:
#     print('大兄弟出错了...')
# else:
#     print('程序正常执行没有错误...')
# print('java')
# 结果:
# hello
# 3.0
# 程序正常执行没有错误...
# java

# print('hello')
# try:
#     print(6/0)
# except:
#     print('大兄弟出错了...')
# else:
#     print('程序正常执行没有错误...')
# print('java')
# 结果:
# hello
# 大兄弟出错了...
# java

异常对象和异常的传播

# print(10/0)# ZeroDivisionError: division by zero
# def fn():
#     print(10/0)
#     print('我是fn')
# fn()
# 结果:
# Traceback (most recent call last):
#   File "F:/python exerciese/209.py", line 5, in <module>
#     fn()
#   File "F:/python exerciese/209.py", line 3, in fn
#     print(10/0)
# ZeroDivisionError: division by zero

# def fn():
#     print(10/0)
#     print('我是fn')
# try:
#     fn()
# except:
#     pass
# 结果:为空,没有报错
# "F:\python exerciese\venv\Scripts\python.exe" "F:/python exerciese/209.py"
#
# Process finished with exit code 0

# def fn():
#     print('我是fn')
#     print(10 / 0)
# try:
#     fn()
# except:
#     pass
# 把print(10/0)放在print('我是fn')下面,结果是 我是fn

# def fn():
#     print('我是fn')
#     print(10/0)
# def fn2():
#     print('我是fn2')
#     fn()
# def fn3():
#     print('我是fn3')
#     fn2()
# fn3()
# 结果:
# "F:\python exerciese\venv\Scripts\python.exe" "F:/python exerciese/209.py"
# 我是fn3
# 我是fn2
# 我是fn
# Traceback (most recent call last):
#   File "F:/python exerciese/209.py", line 44, in <module>
#     fn3()
#   File "F:/python exerciese/209.py", line 43, in fn3
#     fn2()
#   File "F:/python exerciese/209.py", line 40, in fn2
#     fn()
#   File "F:/python exerciese/209.py", line 37, in fn
#     print(10/0)
# ZeroDivisionError: division by zero

# def fn():
#     print('我是fn')
#     print(10/0)
# def fn2():
#     print('我是fn2')
#     fn()
# def fn3():
#     print('我是fn3')
#     fn2()
# # fn3()
# print(ZeroDivisionError)
# "F:\python exerciese\venv\Scripts\python.exe" "F:/python exerciese/209.py"
# <class 'ZeroDivisionError'>

# print('异常出现前')
# try:
#     print(10 / 0)
#     print(a)
#     # print(10 / 0)print(a)哪个在上,哪个在下,结果不一样
# except NameError:
#     # except后面不跟任何的内容,它会捕获所有的异常
#     # except后面跟着一个异常的类型,那么此时它就会捕获该类型的异常
#     # print('处理异常的逻辑')
#     print('出现NameError异常啦')
# except ZeroDivisionError:
#     print('出现ZeroDivisionError异常啦')
# print('异常出现后')

# print('异常出现前')
# lst = [1,2,3]
# try:
#     # list + 0
#     print(10/2)
# except Exception as e:
# # Exception是所有异常类的父类,如果except后面跟的是Exception它会捕获所有的异常
#     print('出现异常啦',e,type(e))
# finally:
#     print('无论是否出现异常,哥们都会执行')
# print('异常出现后')
# 结果:
# "F:\python exerciese\venv\Scripts\python.exe" "F:/python exerciese/209.py"
# 异常出现前
# 5.0
# 无论是否出现异常,哥们都会执行
# 异常出现后

文件的打开

# 用python来对计算机中的各种文件进行增删改查的操作 I/O(Input/Output)
'''
1 打开文件
2 对文件进行各种操作(读、写)
3 关闭文件
'''
# open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
# open()函数是有一个返回值,表示当前的文件对象
# 如果目标文件和当前文件是在同一目录下,则直接使用文件即可
# 如果目标文件和当前文件是不在同一目录下,则接使用目标文件的绝对路径
file_name = 'demo.txt'
print(file_name)
file_obj = open(file_name)# 打开对应的文件
file_name = 'F:\python exerciese\day1\demo1.txt'
file_c = 'day1\demo1.txt'
print(file_obj)
print(file_name)
print(file_c)
file_name = 'D:\PPDownload\demo2.txt'
print(file_name)
"F:\python exerciese\venv\Scripts\python.exe" "F:/python exerciese/214.py"
demo.txt
<_io.TextIOWrapper name='demo.txt' mode='r' encoding='cp936'>
F:\python exerciese\day1\demo1.txt
day1\demo1.txt
D:\PPDownload\demo2.txt

关闭文件

# file_name = 'demo.txt'
# file_obj = open(file_name)
# read()是读取文件的内容,将读取到的内容作为字符串返回
# content = file_obj.read()
# print(content)

# 关闭文件
# 调用close()方法来关闭
# file_obj.close()
# file_obj.read()
# 结果:
# Traceback (most recent call last):
#   File "F:/python exerciese/关闭文件.py", line 10, in <module>
#     file_obj.read()
# ValueError: I/O operation on closed file.
# 关闭之后再读取就出现错误

# with...as...语句
# with open(file_name) as file_obj:
    # 在with语句中可以直接使用file_obj来对文件进行操作
    # 一旦with语句中代码块结束,会自动close()
    # print(file_obj.read())
# print(file_obj.read())# ValueError: I/O operation on closed file.
# 因为with语句中的代码块结束,自动close()

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

读取文件

读取文件.py

'''
open()来打开一个文件,这个文件是可以分为二种类型
1 是纯文本文件(使用utf-8等编码编写的文件就是文本文件)
2 二进制文件(图片、音频、视频...)
open()打开文件的时候,默认是以文本文件的形式打开的
'''
file_name = 'demo2.txt'
try:
    with open(file_name,encoding='utf-8') as file_obj:
        # 通过read()来读取文件中的内容
        content = file_obj.read()
        print(content)
except FileNotFoundError:
    print(f'{file_name} 文件不存在')

demo2.py

关关雎鸠
在河之洲
窈窕淑女
君子好逑

较大文件的读取

较大文件的读取.py

file_name = 'demo.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)
        # print(len(content))
except FileNotFoundError:
    print(f'{file_name} 文件不存在')
结果:
"F:\python exerciese\venv\Scripts\python.exe" "F:/python exerciese/较大文件的读取.py"
Over the years, the weekly commutes to visit my father became rituals. Eventually, after several
yea
rs, we were allowed real visits when he was moved to a lower-security facility—the kind
of visits wh
ere you can hug and tickle, where a conversation’s connection doesn’t depend
on the distorted and cr
ackly voice coming through the telephone, where words can be freely
exchanged without the clock tick
ing, reminding you that time is slipping, moving faster than
it should, faster than you’d like.

demo.py

Over the years, the weekly commutes to visit my father became rituals. Eventually, after several
years, we were allowed real visits when he was moved to a lower-security facility—the kind
of visits where you can hug and tickle, where a conversation’s connection doesn’t depend
on the distorted and crackly voice coming through the telephone, where words can be freely
exchanged without the clock ticking, reminding you that time is slipping, moving faster than
it should, faster than you’d like.

其他的读取方式.py

file_name = 'demo.txt'
with open(file_name) as file_obj:
    
    # print(file_obj.read())
    # readline()用来读取一行
    # print(file_obj.readline(),end='')
    # print(file_obj.readline())
    
    # readlines() 该方法一行一行读取,将结果返回到一个列表
    # r = file_obj.readlines()
    # print(r[0])

文件的写入

文件的写入.py

file_name = 'demo3.txt'
with open(file_name,'w',encoding='utf-8') as file_obj:
    # w表示的可写 使用w写入文件的时候,如果文件不存在就会创建文件
# 并写入内容,如果文件存在则会覆盖原文件的内容
    # write()向文件写入内容
    # file_obj.write('晚上好')
    file_obj.write('大家好\n')
    file_obj.write('abc')
    file_obj.write('bcd\n')
    # file_obj.write(456) 小括号里必须是字符串
    # TypeError: write() argument must be str, not int
    file_obj.write('456')
    # file_obj.write(str(456))
    # 换行是在小括号里加入\n

demo3.txt

大家好
abcbcd
456

文件的写入.py

file_name = 'demo3.txt'
with open(file_name,'a',encoding='utf-8') as file_obj:
    # a表示的是追加
    # w表示的可写 使用w写入文件的时候,如果文件不存在就会创建文件
# 并写入内容,如果文件存在则会覆盖原文件的内容
    # write()向文件写入内容
    # file_obj.write('晚上好')
    # file_obj.write('大家好\n')
    # file_obj.write('abc')
    # file_obj.write('bcd\n')
    # file_obj.write(456) 小括号里必须是字符串
    # TypeError: write() argument must be str, not int
    # file_obj.write('456')
    # file_obj.write(str(456))
    # 换行是在小括号里加入\n
    file_obj.write('hahaha')
    file_obj.write('heiheihei')

demo3.txt

大家好
abcbcd
456hahahaheiheihei

操作二进制文件

# file_name = r'C:\Users\Administrator\Desktop\kalimba.mp3'
# with open(file_name,'r') as file_obj:
#     print(file_obj.read(100))
# UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 21: illegal multibyte sequence

file_name = r'C:\Users\Administrator\Desktop\kalimba.mp3'
with open(file_name,'rb') as file_obj:
    print(file_obj.read(100))
# 结果:
# b'ID3\x04\x00\x00\x00\x00\x08?TIT2\x00\x00\x00\x0b\x00\x00\x01\xff\xfe\xfef\xcf~\xc3_\xbcuTPE1\x00\x00\x00\t\x00\x00' \
# b'\x01\xff\xfeSS\x9dOwZTALB\x00\x00\x00\r\x00\x00\x01\xff\xfet\x87v\x87\xc5`\x8bNI\x00\x00\x00\x00\x00\x00\x00\x00\x00' \
# b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
file_name = r'C:\Users\Administrator\Desktop\kalimba.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:
        # 定义读取的大小
        chuck = 1024 * 100
        while True:
            # 读取内容
            count = file_obj.read(chuck)
            # 内容读取完毕
            if not count:
                break
            # 将读取到的内容写入数据
            new_obj.write(count)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值