从打开的文件中获取行号python

Sky*_*ler 2 python parsing with-statement

我编写了这个小的Python 2.7原型脚本,尝试从格式化的输入文件中读取指定的行(在本例中为3,4,5行).我将在稍后解析此数据并对输入进行操作以构造其他文件.

来自sys import argv

def comparator (term, inputlist):
    for i in inputlist:
        if (term==i):
            return True
    print "fail"
    return False

readthese = [3,4,5]

for filename in argv[1:]:
    with open(filename) as file:
        for line in file:
            linenum=#some kind of way to get line number from file
            if comparator(linenum, readthese):
                print(line)
Run Code Online (Sandbox Code Playgroud)

我修复了我用脚本找到的所有错误,但目前我还没有看到从文件中获取行号.它与从文件对象中提取行号有点不同,因为如果我没有弄错,文件是一个类而不是对象.有没有我可以拉输入文件的行号?

我认为我的很多困惑可能源于我对我的陈述所做的事情,所以如果有人也可以解释我在这条线路上做了多少才会很棒.

mgi*_*son 6

你可以只enumerate使用文件对象,因为enumerate可以迭代任何东西......

for line_number, line in enumerate(file):
    if comparator(line_number, line):
        print line
Run Code Online (Sandbox Code Playgroud)

注意,此索引从0开始 - 如果您希望第一行为1,只需告诉enumerate您要启动的位置:

for line_number, line in enumerate(file, 1):
    ...
Run Code Online (Sandbox Code Playgroud)

注意,我建议不要使用名称file- 在python2.x上,file是一种类型,所以你有效地遮蔽内置(虽然很少使用...).