Python - with
Tip for reading files using with
with man page
# Bad example
f = open('some.txt')
text = f.read()
for line in text.split('\n'):
print(line)
f.close()
# Better example
with open('some.txt') as f:
for line in f:
print(line)
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.