ITPub博客

首页 > IT职业 > IT图书 > python中open和with open有什么区别?

python中open和with open有什么区别?

IT图书 作者:canyoumail 时间:2021-09-11 10:04:51 0 删除 编辑

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

一、open函数

一般是使用 open() 和 close() 组合来打开和关闭文件。

filemame = open('file', mode='r') 

for line in filename.readlines():

    print(line)

filename.close()

1、open()函数是Python内置的用于对文件的读写操作,返回的是文件的流对象。

2、python代码在不同的平台环境中使用的默认编码方式不同,有可能会发生编译出错的问题。

二、with open函数

用于创建一个临时的运行环境,不再需要访问文件后自动将其关闭,运行环境中的代码执行完后自动安全退出环境。

with open('file', mode='r') as filename

    for line in filename.readlines():

        print(line)

1、在这个程序中,调用了open(),但没有调用close();

2、通过使用关键字 with,可让python去确定:打开文件,并在需要时使用它,python自会在合适的时候自动将其关闭。

以上就是python中open和with open的区别,这样你应该对他们有所理解了吧,在不同的情况用不同的函数,一定不要搞混了哟~

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3005/viewspace-2831591/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-13

  • 博文量
    76
  • 访问量
    464