我正在尝试创建一个函数,给定一个 csv 文件路径和关键字,它可以返回关键字的行号和关键字之后下一个空行的行号。目前,代码按我希望的方式工作,但我遇到了检测空行的问题。该if (row[0] == 0) and (int(reader.line_num) > wordLineNum)
部分代码的条件从不测试True
它应该的情况(这就是我为blankLineNum
上面设置默认值的原因)
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