File Handling Using With
tags: #python/documentation/file_handling
Why is it useful?
When using this method, the file.close() statement is not needed. When the body of the with statement is complete and you stop indenting, Python automatically takes care of closing and cleaning up the file.
with open('filename.ext', 'mode') as file:
# read file
for line in file.readlines():
line = line.rstrip() # remove newline char
print(line)
# continue on with other code