python

超轻量级php框架startmvc

Python简单实现安全开关文件的两种方式

更新时间:2020-04-24 05:35:01 作者:startmvc
本文实例讲述了Python简单实现安全开关文件的两种方式。分享给大家供大家参考,具体如下

本文实例讲述了Python简单实现安全开关文件的两种方式。分享给大家供大家参考,具体如下:

以下代码经Python3.3测试。

方式1:


try:
 file = open('config.ini', 'w')
 print("It's a text file", file=file)
except IOError as err:
 print('File error: ' + str(err))
finally:
 if 'file' in locals():
 file.close()

方式2:


try:
 with open('config.txt', 'w') as file:
 print("It's a text file", file=file)
except IOError as err:
 print('File error: ' + str(err))

Python 安全 开关文件