0

I am trying to filter rows with empty columns and non-empty columns.

I have tried the following:

# ignore rows with null or empty cols
a = filter(lambda x: len(x) > 1 and x[1].strip(), file)

# len of rows with empty cols
b = filter(lambda x: x[1] == '', file)

This helps me ignore the rows with empty columns, but the second filter command is an empty list. What am I doing wrong here?

twingo
  • 119
  • 1
  • 8
  • Please, provide [mre]. Most likely after first filter `file` is at the end of the file and thus there is nothing to iterate in second filter – buran Mar 30 '21 at 19:41
  • Side-note: If you're using the `csv` module, `x` will never equal `''` (it's a `list` or `dict`, not a string), and if you're not using the `csv` module, the lines (with the possible exception of the final line) will all end in newlines, so it would never match the filter condition either. And either way, `filter` doesn't make `list`s on Python 3, so you wouldn't see a `list` in either case. – ShadowRanger Mar 30 '21 at 19:45
  • @ShadowRanger Thanks for pointing that out. I've updated the question. – twingo Mar 30 '21 at 19:46
  • [Solved] The file can not be iterated more than once so I've used `tee` to iterate twice. – twingo Mar 30 '21 at 19:52
  • you may need `data = list(file)` to get all data from file as list - and later you can use `data` many times. OR you would have to use `file.seek(0)` to move to the beginnig of file before you use it next time. – furas Mar 30 '21 at 20:43

0 Answers0