简体   繁体   中英

Close file handle in list comprehension

Let's say I want to read in all the lines from a file and store as a list of strings. I can use:

filename = "/path/to/the/file/data.txt"
fileBuf = [line.strip() for line in open(filename, "r")]

My question is, because the file handle is unnamed, how do I close it? Is it closed automatically?

It is probably garbage collected, but recommended way is to use with context. You could even do it in one line:

with open(filename, "r") as f: fileBuf = [line.strip() for line in f]

You can use with statement Code :

with open(FILENAME, 'r') as f:
     fileBuf = [line.strip() for line in f]

Hope this helps !

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