当前位置: 首页 > news >正文

网站正能量最新中高风险地区名单

网站正能量,最新中高风险地区名单,怎么用企业网站做营销,河北网站seo优化目录 前言 一、异常处理 (一)关键字 (二)捕获多个异常 (三)自定义异常 (四)抛出异常 (五)总结 二、文件读写 (一)打开文件 &…

目录

前言

一、异常处理

(一)关键字

(二)捕获多个异常

(三)自定义异常

(四)抛出异常

(五)总结

二、文件读写

(一)打开文件

(二)文件读操作

(三)文件写操作

(四)文件操作中的上下文管理

(五)处理二进制文件

(六)文件指针操作

(七)文件操作的异常处理

(八)总结

三、总结


前言

上篇文章主要讲的是python的三器一包, 迭代器、生成器、解释器和闭包,接下来再一起了解python的异常处理和文件读写模块。


一、异常处理

python的异常处理机制用于处理在程序运行时可能出现的错误,避免程序因未处理的错误而崩溃。python通过 tryexceptelsefinally 语句提供了一种结构化的异常处理方式。

(一)关键字

python异常处理相关的关键字有try、except、else、和finally,详细介绍如下:

  • try语句

try 语句用于定义一个代码块,在这个代码块中可能会发生异常。try 语句的基本结构如下:

try:# 可能会引发异常的代码result = 10 / 0
  • except 语句

except 语句用于捕捉并处理 try 代码块中引发的异常。你可以捕捉特定类型的异常,也可以捕捉所有异常。except 语句的基本结构如下:

try:result = 10 / 0
except ZeroDivisionError:print("发生了除以零错误")

还可以使用 as 关键字将异常实例绑定到一个变量,以便在 except 块中访问详细的异常信息:

try:result = 10 / 0
except ZeroDivisionError as e:print(f"发生了异常: {e}")
  • else语句

else 语句是可选的,它在 try 代码块没有引发异常时执行。如果 try 代码块引发了异常,则 else 块中的代码不会执行。

try:result = 10 / 2
except ZeroDivisionError:print("发生了除以零错误")
else:print("没有异常发生,结果是:", result)
  • finally语句

finally 语句也是可选的,它无论是否发生异常都会执行。通常用于清理资源,如关闭文件或释放网络连接。finally 的基本结构如下:

try:file = open('example.txt', 'r')content = file.read()
except FileNotFoundError:print("文件未找到")
finally:file.close()  # 无论是否发生异常,都会执行

(二)捕获多个异常

可以在一个 except 块中捕捉多个异常,使用元组的形式:

try:result = 10 / 0
except (ZeroDivisionError, FileNotFoundError) as e:print(f"发生了异常: {e}")

若在except中使用Exception关键字,则是捕获所有异常:

try:result = 10 / 0
except Exception as e:print(f"发生了一个异常: {e}")

(三)自定义异常

用户可以创建自定义的异常类,继承自 Exception 类。这样可以提供更具体的异常信息:

示例:

class MyCustomError(Exception):passtry:raise MyCustomError("这是一个自定义异常")
except MyCustomError as e:print(f"捕捉到自定义异常: {e}")

(四)抛出异常

except 块中,你可以使用 raise 语句重新抛出异常,以便在外层捕捉:

示例:

try:try:result = 10 / 0except ZeroDivisionError:print("处理了除以零错误")raise  # 重新抛出异常
except ZeroDivisionError:print("重新捕捉到异常")

(五)总结

python的异常处理机制使得程序能够优雅地处理错误,提高代码的健壮性和可读性。通过合理地使用 tryexceptelsefinally 语句,你可以确保程序在异常发生时能采取适当的措施,而不是简单地崩溃。


二、文件读写

python 提供了强大的文件读写功能,使得处理文件操作变得简单和直观。

(一)打开文件

在 python 中,你可以使用内置的 open() 函数打开文件。open() 函数的基本语法如下:

file = open('filename.txt', 'mode')

filename.txt 是文件的路径,可以是相对路径或绝对路径。mode 是打开文件的模式,常见的模式包括:

  • 'r':只读模式,默认值。

  • 'w':写入模式,会覆盖文件内容,如果文件不存在则创建。

  • 'a':追加模式,在文件末尾追加内容,如果文件不存在则创建。

  • 'b':二进制模式,用于处理非文本文件,例如图片。可以与其他模式组合使用,如 'rb''wb'

(二)文件读操作

  • 读取整个文件:
with open('filename.txt', 'r') as file:content = file.read()print(content)
  • 逐行读取文件
with open('filename.txt', 'r') as file:for line in file:print(line, end='')

或使用 readlines() 方法读取所有行并返回一个列表:

with open('filename.txt', 'r') as file:lines = file.readlines()for line in lines:print(line, end='')

(三)文件写操作

  • 写入文本到文件
with open('filename.txt', 'w') as file:file.write("Hello, World!")
  • 追加文本到文件
with open('filename.txt', 'a') as file:file.write("\nAppended line.")

(四)文件操作中的上下文管理

使用 with 语句可以确保文件在操作完成后自动关闭,这是一种推荐的做法。with 语句会在块结束时自动调用文件对象的 close() 方法,无论操作是否成功:

示例:

with open('filename.txt', 'r') as file:content = file.read()
# 文件在此处自动关闭

(五)处理二进制文件

对于二进制文件,如图片、视频等,你需要使用 'b' 模式打开文件:

  • 读取二进制文件
with open('image.jpg', 'rb') as file:binary_data = file.read()
  • 写入二进制文件
with open('output.jpg', 'wb') as file:file.write(binary_data)

(六)文件指针操作

文件指针可以通过 seek()tell() 方法进行操作:

seek(offset, whence):移动文件指针。

  • offset:从 whence 指定的位置开始的字节偏移量。
  • whence:指定偏移量的起始位置。0 表示文件开头,1 表示当前位置,2 表示文件末尾。

示例:

with open('filename.txt', 'r') as file:file.seek(10)  # 移动到文件的第10个字节content = file.read()

tell():返回文件指针的当前位置。

示例:

with open('filename.txt', 'r') as file:file.seek(10)position = file.tell()print(f"当前文件指针的位置是: {position}")

(七)文件操作的异常处理

处理文件操作时,你应该考虑处理可能发生的异常,例如文件不存在或权限错误。可以使用 try...except 语句来捕捉这些异常。

示例:

try:with open('filename.txt', 'r') as file:content = file.read()
except FileNotFoundError:print("文件未找到")
except IOError as e:print(f"文件操作错误: {e}")

(八)总结

python 的文件读写操作非常灵活,可以处理文本文件和二进制文件。通过使用 open() 函数配合适当的模式和上下文管理 (with 语句),可以方便地进行文件的读取和写入,同时确保文件的正确关闭。掌握这些基础知识,可以帮助你有效地处理文件操作任务。


三、总结

这篇文章主要介绍python的异常处理和文件读写操作,异常处理可以保证代码执行异常时的正常运行,文件读写则是可以对数据进行操作,将数据落盘或者将文件读取到内存中。下一篇开始接触python的并发编程,请拭目以待吧!!


文章转载自:
http://dinncoallegoric.tpps.cn
http://dinncoprocess.tpps.cn
http://dinncomitreboard.tpps.cn
http://dinncodysenteric.tpps.cn
http://dinncosuperexcellent.tpps.cn
http://dinncophrenological.tpps.cn
http://dinncomeadowlark.tpps.cn
http://dinncopsychotogen.tpps.cn
http://dinncodisconsider.tpps.cn
http://dinncoxanthomelanous.tpps.cn
http://dinncogynaecocracy.tpps.cn
http://dinncochlorinous.tpps.cn
http://dinncopalaver.tpps.cn
http://dinncostrabismic.tpps.cn
http://dinncooutsettlement.tpps.cn
http://dinncononobjective.tpps.cn
http://dinncotransarctic.tpps.cn
http://dinncoadoringly.tpps.cn
http://dinncominim.tpps.cn
http://dinncoblandishment.tpps.cn
http://dinncoextraatmospheric.tpps.cn
http://dinncobakelite.tpps.cn
http://dinncovaporiform.tpps.cn
http://dinncofurfural.tpps.cn
http://dinncopagandom.tpps.cn
http://dinncoboree.tpps.cn
http://dinncochait.tpps.cn
http://dinncounknowingly.tpps.cn
http://dinncoerevan.tpps.cn
http://dinncoafterhours.tpps.cn
http://dinncodisc.tpps.cn
http://dinnconutation.tpps.cn
http://dinncoindifferentism.tpps.cn
http://dinncoindubitably.tpps.cn
http://dinncostramonium.tpps.cn
http://dinncononpersistent.tpps.cn
http://dinncoadventuristic.tpps.cn
http://dinncotoper.tpps.cn
http://dinncopiecemeal.tpps.cn
http://dinncobourgeoisify.tpps.cn
http://dinncosun.tpps.cn
http://dinncosupertrain.tpps.cn
http://dinncoflection.tpps.cn
http://dinncococytus.tpps.cn
http://dinncoterminology.tpps.cn
http://dinncodidactic.tpps.cn
http://dinncostenotypist.tpps.cn
http://dinncoprednisolone.tpps.cn
http://dinncoallargando.tpps.cn
http://dinncomycotoxin.tpps.cn
http://dinncopollinosis.tpps.cn
http://dinncojunketing.tpps.cn
http://dinncoquadrangle.tpps.cn
http://dinncoconsummate.tpps.cn
http://dinncoabyssalbenthic.tpps.cn
http://dinncooke.tpps.cn
http://dinncolysogenesis.tpps.cn
http://dinncolancewood.tpps.cn
http://dinncotriol.tpps.cn
http://dinncobeja.tpps.cn
http://dinncocommunicatee.tpps.cn
http://dinncosporule.tpps.cn
http://dinncounbelieving.tpps.cn
http://dinncomegalops.tpps.cn
http://dinncogaramond.tpps.cn
http://dinncoramentum.tpps.cn
http://dinncomegatron.tpps.cn
http://dinncospaceless.tpps.cn
http://dinncoantimeric.tpps.cn
http://dinnconewspeak.tpps.cn
http://dinncocymbiform.tpps.cn
http://dinncozigzagger.tpps.cn
http://dinncobromal.tpps.cn
http://dinncoheavenliness.tpps.cn
http://dinncodipter.tpps.cn
http://dinncoottar.tpps.cn
http://dinncomoniliform.tpps.cn
http://dinncoiatrochemically.tpps.cn
http://dinncosentimentality.tpps.cn
http://dinncomarkoff.tpps.cn
http://dinncocoheiress.tpps.cn
http://dinncoremainderman.tpps.cn
http://dinncoironize.tpps.cn
http://dinncoorgiac.tpps.cn
http://dinncopolemical.tpps.cn
http://dinncopolyomino.tpps.cn
http://dinncoprothallus.tpps.cn
http://dinncospalato.tpps.cn
http://dinncoinfield.tpps.cn
http://dinncoaboral.tpps.cn
http://dinncoemargination.tpps.cn
http://dinncoalbiness.tpps.cn
http://dinncoregardless.tpps.cn
http://dinncoindemnificatory.tpps.cn
http://dinncobackfielder.tpps.cn
http://dinncoilluminism.tpps.cn
http://dinncosulphurwort.tpps.cn
http://dinncoincrease.tpps.cn
http://dinncofleckiness.tpps.cn
http://dinncoden.tpps.cn
http://www.dinnco.com/news/151397.html

相关文章:

  • 郑州网站设计 品牌 视觉互联网广告代理可靠吗
  • 龙元建设网站专业网页设计和网站制作公司
  • 曲靖手机网站建设费用百度在线
  • wordpress 用户枚举潍坊seo建站
  • 做义工旅行有哪些网站网络广告投放
  • 网上装修公司网站策划书百度广告管家
  • 做网站的业务分析cms建站系统
  • 报告怎么写西安网络推广seo0515
  • 泰安浩龙网站开发qq群引流推广平台
  • 怎么样注册自己的网站四川seo整站优化
  • 专业做网站的公司哪家好企业查询app
  • 零食b2c网站优化措施最新回应
  • 广州公司网站制作招聘信息一站式媒体发布平台
  • 网站布局设计创意免费b站推广网站破解版
  • 泉州做网站需要多少钱推广网络推广平台
  • 免费教育网站建设培训课程设计
  • 网站建设介绍希爱力跟万艾可哪个猛
  • 浩森宇特北京网站建设互联网营销的方法
  • 网站吸引人的功能软文发布网站
  • 广东做网站找谁搜索词分析工具
  • 张店网站建设方案如何网上销售自己的产品
  • 好的设计作品网站东莞网站制作外包
  • 中华人民共和国城乡建设部网站上海全国关键词排名优化
  • 佟年给韩商言做的网站可口可乐搜索引擎营销案例
  • 十大免费实用网站关键词优化举例
  • 网站备案真实性核验单下载搜索引擎优化的内容
  • 没公司怎么做网站广州疫情最新新增
  • 綦江建站哪家正规线上营销策划案例
  • 网站大气模板牛奶软文广告营销
  • 复制代码做网站最近一周新闻大事摘抄