Use File Iterator
Documentation Index
Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
Use this file to discover all available pages before exploring further.
Sourcery refactoring id: use-file-iterator
Section titled “Sourcery refactoring id: use-file-iterator”Description
Section titled “Description”Use the in-built file iterator rather than calling readlines()
Before
Section titled “Before”with open("foo") as f: for line in f.readlines(): print(line)with open("foo") as f: for line in f: print(line)Explanation
Section titled “Explanation”The file object that Python returns when you open a file is a lazy iterator over
that file’s lines. This means that there is no need to call readlines to
iterate over it. Iterating directly is shorter, and also does not load the whole
file into memory with a list object ( which readlines does) so can be more
performant.