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
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