0

I'm attempting to create a function that, given a csv file path and keyword, can return the line number of the keyword and the line number of the next blank line after the keyword. Currently, the code works the way I want it to for the keyword, but I'm running into issues with detecting a blank line. The if (row[0] == 0) and (int(reader.line_num) > wordLineNum) condition of that part of the code never tests True in cases it should (which is why I set a default value for blankLineNum above)

def lineFinder (keyword, path): # returns the line number and next blank line within a csv 
                                # file given a keyword
   wordLineNum = 0 #hard coded will remove at some point
   blankLineNum = 8 #will remove once function works as intended
   csvfile = open(path, 'r')
   reader = csv.reader(csvfile)

   for row in reader:
      if str(keyword) in row:
         wordLineNum = int(reader.line_num)

   for row in reader:
      if (row[0] == 0) and (int(reader.line_num) > wordLineNum):
          blankLineNum = int(reader.line_num)

   return wordLineNum , blankLineNum
martineau
  • 119,623
  • 25
  • 170
  • 301
mbarz
  • 13
  • 1

1 Answers1

1

Your code will find the last keyword in the file. This might be what's intended, just wanted to point out, that you're overwriting the value every time the keyword is found.

Under the if in the first loop, you can add a check:

for row in reader:
    if str(keyword) in row:
        wordLineNum = int(reader.line_num)
    if wordLineNum > 0 and row[0] == 0):
        blankLineNum = int(reader.line_num)
        # Remove the next comment if you want to return the first blank line
        # return wordLineNum , blankLineNum
        
#return the last blank line
return wordLineNum , blankLineNum
Lennart Steinke
  • 584
  • 5
  • 11
  • 1
    Thank you! For the most part, the keyword will only appear once in the file but there are a couple exceptions so that is very useful to know/keep in mind! This code worked for me with a slight tweak. I was getting an `IndexError: list index out of range` on the line `if (wordLineNum >0) and (row[0] ==0):`. I instead used `len(row) < 1` to check if the row was blank and it worked perfectly for me. – mbarz Jul 09 '20 at 19:48
  • That was something I actually wondered as well. Bu I thought it would be better to use your checking code in case "empty lines" are filled with zeros and nil values. :) – Lennart Steinke Jul 10 '20 at 10:13