0

What is going on here?

with open('contractors.txt','r') as in_file:  
    stripped = (line.strip() for line in in_file)   
    lines = (line for line in stripped if line)

Is this a syntactic equivalent to:

for line in in_file:
    stripped = line.strip()
for line in stripped:
    lines =  line
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149

1 Answers1

0

The "compacted for loops" are called generator expressions, which are more-or-less equivalent to list comprehensions that return generators instead of lists.

In the code you're looking at, the stripped generator expression str.strip()s each line of the opened file, and the lines generator expression drops any blank lines from stripped. The end result is a generator (lines) that, when iterated over, will generate the stripped version of the non-empty lines of the file.

It's important to note that since you're just working with generators, after these lines are run nothing has actually been read from the file yet. If you end the with block, the file will be closed and attempting to pull anything from lines will result in an I/O error. So anything you want to do with it has to be done within that block.

glibdud
  • 7,550
  • 4
  • 27
  • 37