Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
以下链接的解决方案没有解决我的问题:如何关闭我从未分配给变量的文件对象?
如何关闭以下行中的文件?
file = open(filename, 'r').read().splitlines()
这样的文件会自动被垃圾收集并关闭。但是,通常应该避免这种模式。相反,请使用以下with语句:
with
with open(filename, 'r') as fd: lines = fd.read().splitlines()