千家信息网

如何用python的Try finally语句和with语句安全的读文件

发表于:2024-09-23 作者:千家信息网编辑
千家信息网最后更新 2024年09月23日,这篇文章主要介绍了如何用python的Try finally语句和with语句安全的读文件的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇如何用python的Try fin
千家信息网最后更新 2024年09月23日如何用python的Try finally语句和with语句安全的读文件

这篇文章主要介绍了如何用python的Try finally语句和with语句安全的读文件的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇如何用python的Try finally语句和with语句安全的读文件文章都会有所收获,下面我们一起来看看吧。

Try...finally语句

输入:

#!/usr/bin/python

# Filename: finally.py

import time

try:

f = open('poem.txt')

while True:

# our usual file-reading idiom

line = f.readline()

if len(line) == 0:

break

print(line, end='')

time.sleep(2)

# To make sure it runs for a while

except KeyboardInterrupt:

print('!! You cancelled the reading from the file.')finally:

f.close()

print('(Cleaning up: Closed the file)')

输出:

$ python finally.py

Programming is fun

When the work is done

if you wanna make your work also fun:

!! You cancelled the reading from the file.

(Cleaning up: Closed the file)

解释:

当我们进行文件的操作时,为了保证有异常事件发生时,我们可以正常的关闭文件,所有我们使用了 try...finally函数。当有异常时,抛出异常,并且关闭文件操作。

本例中先打开文件操作,然后读文件,为了延长 try里运行时间,我们加入了sleep(2)停顿两秒时间,在此期间我们通过强制的 Ctrl C操作来人为的制造中断,造成异常,进入finally正常的执行了文件的关闭操作。

with语句

输入:

#!/usr/bin/python

# Filename: using_with.py

with open("poem.txt") as f:

for line in f:

print(line, end='')

输出:

$ python using_with.py

Programming is fun

When the work is done

解释:

与try...finally语句的功能一样,with函数也能够进行保护文件的正常操作。在遇到异常时,进行文件关闭。

关于"如何用python的Try finally语句和with语句安全的读文件"这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对"如何用python的Try finally语句和with语句安全的读文件"知识都有一定的了解,大家如果还想学习更多知识,欢迎关注行业资讯频道。

0