Skip to content Skip to sidebar Skip to footer

Python - Skipping Lines While Using Csv.dictreader

This is follow up to this question - 2d list in python The answer by @Kroolik addresses my issue, but I'm stuck on another thing consider my files is as follows junk.... junk.... j

Solution 1:

You can loop within the loop, getting the next lines until you are at the end:

forrowin version_new:
   if "JID" inrow:
      # in required section, loop until end:
      forrowin version_new:
          if "Total text" inrow:
              break
          list_top_version_new.append(row)
    # Anything outside of the required section is ignored.

Note that row.split() isn't needed; csv.DictReader gives you a dictionary object, with the row already split out into values already.

list_top_version_new is also a list of dictionaries, no need to put those through csv.DictReader()again. And since you are already looping over that section of your input file, why not just directly in that loop do your work? So, instead of a separate loop over list_top_version_new at the end, replace list_top_version_new.append(row) with whatever work you need to do with the row:

forrowin version_new:
   if "JID" inrow:
      # in required section, loop until end:
      forrowin version_new:
          if "Total text" inrow:
              break
          print(row)

Post a Comment for "Python - Skipping Lines While Using Csv.dictreader"