前言
当我们检测到文件之后就可以读取其中的内容,读取所用到的函数是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),敬请期待~