函数,给定一个csv文件路径和一个关键字,returns关键字的行号和下一个空行的行号
Function that, given a csv file path and a keyword, returns the line number of the keyword and the line number of the next blank line
我正在尝试创建一个函数,在给定 csv 文件路径和关键字的情况下,可以 return 关键字的行号和关键字后下一个空行的行号。目前,代码按照我希望的方式为关键字工作,但我 运行 遇到检测空行的问题。该部分代码的 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
您的代码将找到文件中的最后一个关键字。这可能是预期的,只是想指出,每次找到关键字时您都会覆盖该值。
在第一个循环的if下,可以加一个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
我正在尝试创建一个函数,在给定 csv 文件路径和关键字的情况下,可以 return 关键字的行号和关键字后下一个空行的行号。目前,代码按照我希望的方式为关键字工作,但我 运行 遇到检测空行的问题。该部分代码的 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
您的代码将找到文件中的最后一个关键字。这可能是预期的,只是想指出,每次找到关键字时您都会覆盖该值。
在第一个循环的if下,可以加一个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