如何在不分配变量的情况下关闭python中的文件 [英] How to close a file in python without assigning a variable

查看:97
本文介绍了如何在不分配变量的情况下关闭python中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打开python后如何关闭文件:

line = open(file.txt,r ).readlines()[7]

解决方案

最好使用上下文管理器。这将在块的结尾自动关闭文件,并且不依赖garbarge集合的实现细节。

  with open (file.txt,r)作为f:
line = f.readlines()[7]


How do I close a file in python after opening it this way:

line = open("file.txt", "r").readlines()[7]

解决方案

Best to use a context manager. This will close the file automatically at the end of the block and doesn't rely on implementation details of the garbarge collection

with open("file.txt", "r") as f:
    line = f.readlines()[7]

这篇关于如何在不分配变量的情况下关闭python中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆