我一直在寻找解决方案,但我还没找到.所以,我试图在我的csv文件中找到特定输入的行号.例如,让这是我正在解析的csv文件 -
a b c d
这是一个包含100行和1列的文件.所以我在输入"d"中输入,我应该得到4.我试过这个代码,但它给了我没有 -
def find_index(input): o = open('products.csv', 'rU') myData = csv.reader(o) index = 0 for row in myData: if row == input: return index else : index+=1
我是csv模块的新手,所以如果我是傻瓜,请原谅我.谢谢!
编辑 - 我尝试了每个人的解决方案,所有人都只返回无.可能有什么不对?这是'rU'标志吗?因为如果我删除它,我得到这个错误 - 对于myData中的行:
Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
hd1.. 5
您正在寻找reader对象的line_num成员:
with open('products.csv') as o: myData = csv.reader(o): for row in myData: if row == input: return myData.line_num
请注意这一点is not the same as the number of records returned, as records can span multiple lines.
但是,通常,如果您的记录终结符是换行符,它们将是相同的.如果您需要进一步的帮助,请发表评论.
您正在寻找reader对象的line_num成员:
with open('products.csv') as o: myData = csv.reader(o): for row in myData: if row == input: return myData.line_num
请注意这一点is not the same as the number of records returned, as records can span multiple lines.
但是,通常,如果您的记录终结符是换行符,它们将是相同的.如果您需要进一步的帮助,请发表评论.