简体   繁体   中英

Will `readlines()` close the opened file in python?

In Python, will

file_name = ''
content_list = open(file_name, 'r').readlines()

automatically close the opened file?

No, you should use the Context Manager for it:

file_name = 'abc.txt'
with open(file_name, 'r') as txtFile:
    content_list = txtFile.readlines()

No, you'd need to use with. Either way, readlines will not close the file.

with open(file_name, 'r') as f:
    content_list = f.readlines()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM