meTchaikovsky
meTchaikovsky

Reputation: 7666

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?

Upvotes: 0

Views: 86

Answers (2)

Kind Stranger
Kind Stranger

Reputation: 1761

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()

Upvotes: 1

Julio S.
Julio S.

Reputation: 970

No, you should use the Context Manager for it:

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

Upvotes: 1

Related Questions