剩下的台词怎么读?python

2024-10-02 18:22:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,它有一些标题行,例如

header1 lines: somehting something
more headers then
somehting something
----

this is where the data starts
yes data... lots of foo barring bar fooing data.
...
...

我已经通过循环和运行file.readlines()跳过了头行,除了循环和合并其余的行之外,我还能如何读取其余的行?

^{pr2}$

Tags: 文件the标题dataismorethiswhere
2条回答

跳过前5行:

from itertools import islice

with open('yourfile') as fin:
    data = list(islice(fin, 5, None))
    # or loop line by line still
    for line in islice(fin, 5, None):
        print line

.readlines()一次性读取文件中的所有数据。第一次通话后没有更多的行要读了。在

您可能想使用.readline()(nos,单数)来代替:

with open('test.txt','r') as fin:
    for _ in range(5): fin.readline()
    rest = "\n".join(fin.readlines())

请注意,因为.readlines()已经返回了一个列表,所以不需要遍历这些项。您也可以使用.read()读取文件的其余部分:

^{2}$

或者,将file对象视为iterable,并使用^{}切片iterable来跳过前五行:

from itertools import islice

with open('test.txt','r') as fin:
    all_but_the_first_five = list(islice(fin, 5, None))

这确实会产生,而不是一个大字符串,但是如果要逐行处理输入文件,那么通常最好还是这样。可以直接在切片和句柄行上循环:

with open('test.txt','r') as fin:
    for line in list(islice(fin, 5, None)):
        # process line, first 5 will have been skipped

不要混合使用file对象作为iterable和.readline();由file对象实现的迭代协议使用一个内部缓冲区来确保.readline()所不知道的效率;在迭代之后使用.readline()很可能会在文件中返回比预期更远的数据。在

相关问题 更多 >