Python编程基础:第三十一节 文件读取Read a File

第三十一节 文件读取Read a File

前言

当我们检测到文件之后就可以读取其中的内容,读取所用到的函数是read()

实践

我们依然以上一节的lyric.txt为例展示如何读取文件中的内容。首先我们使用open()函数打开所要读取的文件:

with open(r"C:\Users\shen_student\Desktop\lyric.txt", encoding="utf-8") as file:
	print(file.read())
>>> End Game
>>> 最终结局
>>> [Chorus: Taylor Swift & Future]
>>> I wanna be your endgame
>>> 我想成为你的最终结局

我们来分析上述代码,open()函数首先指定文件路径,然后指定文件的编码方式,一般而言对于有汉字的文件我们需要使用utf-8进行编码。然后通过read()函数读取文件中的内容并通过print()函数打印出来。
那么如果我们对文件名称拼写错误会发生什么呢?

with open(r"C:\Users\shen_student\Desktop\lyric.tx", encoding="utf-8") as file:
	print(file.read())
>>> FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\shen_student\\Desktop\\lyric.tx'

可见程序报错并中断执行,我们可以借助于之前学习的异常处理相关知识来避免程序中断执行:

try:
    with open(r"C:\Users\shen_student\Desktop\lyric.txt", encoding="utf-8") as file:
        print(file.read())
except FileNotFoundError:
    print("That file was not found :(")
>>> That file was not found :(

可见,此时程序并没有中断,而是打印出文件未找到。
在我们读取文件内容之后,需要将文件关闭,这里我们使用函数close()来实现这个功能:

try:
    with open(r"C:\Users\shen_student\Desktop\lyric.tx", encoding="utf-8") as file:
        print(file.read())
    file.close()
except FileNotFoundError:
    print("That file was not found :(")

以上便是文件读取的全部内容,感谢大家的收藏、点赞、评论。我们下一节将介绍文件写入(Write a File),敬请期待~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值