简体   繁体   English

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

[英]Get line number python from opened file

I wrote this little Python 2.7 prototype script to try and read specified lines (in this example lines 3,4,5) from a formatted input file. 我写了这个小的Python 2.7原型脚本,尝试从格式化的输入文件中读取指定的行(在本示例中为第3、4、5行)。 I am going to be later parsing data from this and operating on the input to construct other files. 我将稍后解析此数据并在输入上进行操作以构建其他文件。

from sys import argv 从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)

I fixed all the errors I had found with the script but currently I don't see anyway to get a line number from file. 我修复了在脚本中发现的所有错误,但是目前我仍然看不到从文件中获取行号的问题。 It's a bit different than pulling the line number from a file object since file is a class not an object if I'm not mistakened. 这与从文件对象中提取行号有些不同,因为如果我没有记错的话,文件不是一个对象,而是一个类。 Is there someway I can pull the the line number for my input file? 有什么办法可以拉输入文件的行号吗?

I think a lot of my confusion probably stems from what I did with my with statement so if someone could also explain what exactly I have done with that line that would be great. 我认为我的很多困惑可能源于我对with陈述所做的工作,因此,如果有人也可以解释我对那条线所做的确切工作,那将是很棒的。

You could just enumerate the file object since enumerate works with anything iterable... 您可以enumerate文件对象,因为enumerate可与任何可迭代的对象一起使用...

for line_number, line in enumerate(file):
    if comparator(line_number, line):
        print line

Note, this indexes starting at 0 -- If you want the first line to be 1, just tell enumerate that's where you want to start: 请注意,此索引从0开始-如果您希望第一行为1,只需告诉enumerate这就是您要开始的位置:

for line_number, line in enumerate(file, 1):
    ...

Note, I'd recommend not using the name file -- On python2.x, file is a type so you're effectively shadowing a builtin (albeit a rarely used one...). 请注意,我建议您不要使用名称file -在python2.x上, file是一种类型,因此您可以有效地隐藏内置函数(尽管很少使用...)。

You could also use the list structure's index itself like so: 您还可以像这样使用列表结构的索引本身:

with open('a_file.txt','r') as f:
    lines = f.readlines()
readthese = [3,4,5]
for lineno in readthese:
    print(lines[1+lineno])

Since the list of lines already implicitly contains the line numbers based on index+1 由于名单lines已经隐含包含的行号基于索引+ 1

If the file is too large to hold in memory you could also use: 如果文件太大而无法保存在内存中,则还可以使用:

readthese = [3,4,5]
f = open('a_file.txt','r')
for lineno in readthese:
    print(f.readline(lineno+1))
f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM