从python的第二行开始读取文件

2024-09-27 00:22:03 发布

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

我用python,我不知道怎么做。

我想在文件里读很多行。但我得读第二行。所有的文件都有不同的行,所以我不知道怎么做。

代码示例是它从第一行读取到第16行。 但我必须从第二行读到最后一行。 谢谢您!:)

with open('filename') as fin:
  for line in islice(fin, 1, 16):
    print line

Tags: 文件代码in示例foraswithline
3条回答

您应该能够调用next,并丢弃第一行:

with open('filename') as fin:
    next(fin) # cast into oblivion
    for line in fin:
        ... # do something

这很简单,因为fin是一个生成器。

with open("filename", "rb") as fin:
    print(fin.readlines()[1:])

查看islice的文档

itertools.islice(iterable, stop)
itertools.islice(iterable, start, stop[, step])

Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped. If stop is None, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position. Unlike regular slicing, islice() does not support negative values for start, stop, or step. Can be used to extract related fields from data where the internal structure has been flattened (for example, a multi-line report may list a name field on every third line).

我想你可以告诉它从第二行开始迭代到最后。e、 g

with open('filename') as fin:
    for line in islice(fin, 2, None):  # <--- change 1 to 2 and 16 to None
        print line

相关问题 更多 >

    热门问题