如何使用 Python 在文件中跳过 2 行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16383882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:27:00  来源:igfitidea点击:

How to skip 2 lines in a file with Python?

pythondictionarycountline

提问by UserYmY

I have a series of files and I want to extract a specific number from each of them. In each of the files I have this line:

我有一系列文件,我想从每个文件中提取一个特定的数字。在每个文件中,我都有这一行:

name, registration num

and exactly two lines after that there is the registration number. I would like to extract this number from each file. and put it as a value of a dictionary.Anyone have any idea how it is possible ?

紧接着两行是注册号。我想从每个文件中提取这个数字。并将其作为字典的值。有谁知道这是怎么可能的?

my current code that does not actually work is like below:

我当前实际上不起作用的代码如下所示:

matches=[]
for root, dirnames, filenames in os.walk('D:/Dataset2'):  
    for filename in fnmatch.filter(filenames, '*.txt'):   
        matches.append([root, filename])

filenames_list={}       
for root,filename in matches:
    filename_key = (os.path.join(filename).strip()).split('.',1)[0]

    fullfilename = os.path.join(root, filename)
    f= open(fullfilename, 'r')
    for line in f:
        if "<name, registration num'" in line:
            key=filename_key
            line+=2
            val=line

采纳答案by Inbar Rose

I usually use next()when I want to skip a single line, usually a header for a file.

我通常next()在想跳过一行时使用,通常是文件的标题。

with open(file_path) as f:
    next(f) # skip 1 line
    next(f) # skip another one.
    for line in f:
        pass # now you can keep reading as if there was no first or second line.

Note: In Python 2.6 or earlier you must use f.next()

注意:在 Python 2.6 或更早版本中,您必须使用 f.next()

回答by Cthulhu

I suppose something like that would work...

我想这样的事情会起作用......

f= open(fullfilename, 'r')
for line in f:
    if "name, registration num" in line:
        key=filename_key
        break
f.readline()
res = f.readline()[:-1] #removed trailin newline

回答by jamylak

from itertools import islice
with open('data.txt') as f:
    for line in islice(f, 2, None):
        print line

回答by Tom

Generally speaking, if you want to do something to a python iterator in-loop, like look two ahead, I find a good first place to look is to import itertoolsand look here. In your case, you might benefit from their implementation of consume.

一般来说,如果你想对循环中的 python 迭代器做一些事情,比如向前看两个,我发现一个很好的第一个地方是 to import itertoolsand look here。在您的情况下,您可能会从他们的 consume.

Worth having a look to see if this issue hasn't been covered on SO before. Edit: Indeed- look here, which includes a good discussion of python iterators.

值得一看,看看这个问题之前是否没有在 SO 上讨论过。编辑:确实 - 看这里,其中包括对 python 迭代器的很好的讨论。

回答by varesa

One way would be to load the whole line into an array, and then read the line(s) you want from it. Example

一种方法是将整行加载到一个数组中,然后从中读取您想要的行。例子

A file called testfile contains the following:

名为 testfile 的文件包含以下内容:

A1
B2
C3
D4
E5

A program test.py:

一个程序test.py:

#!/usr/bin/env python

file = open('testfile')
lines = file.readlines()[2:]
file.close()

for line in lines:
    print(line.strip())

Output:

输出:

$./test.py
C3
D4
E5

EDIT: I read the question again, and noticed you just want a single line. Then you could just remove the :, and use f.getlines()[2]to get the third line in a file

编辑:我再次阅读了这个问题,并注意到你只想要一行。然后你可以删除:, 并用于f.getlines()[2]获取文件中的第三行



  • Or you could use f.getline() three times, and just ignore the first two

  • Or you could use a for line in ftype loop, and just ignore the first two line (have an incrementing counter)

  • 或者你可以使用 f.getline() 三次,而忽略前两个

  • 或者您可以使用for line in f类型循环,并忽略前两行(有一个递增计数器)