简体   繁体   English

从python第二行开始读取文件

[英]Read a file starting from the second line in python

I use python and I don't know how to do. 我使用python,但我不知道该怎么做。

I want to read lots of lines in files. 我想阅读文件中的许多行。 But I have to read from second lines. 但是我必须从第二行开始阅读。 All files have different lines, So I don't know how to do. 所有文件都有不同的行,所以我不知道该怎么办。

Code example is that it read from first line to 16th lines. 代码示例是从第一行到第16行进行读取。 But I have to read files from second lines to the end of lines. 但是我必须从第二行到行尾读取文件。 Thank you!:) 谢谢!:)

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

You should be able to call next and discard the first line: 您应该可以呼叫next并丢弃第一行:

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

This is simple and easy because of the nature of fin , being a generator. 由于fin本身就是发电机,因此这很容易。

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

Looking at the documentation for islice 查看islice的文档

itertools.islice(iterable, stop) itertools.islice(可迭代,停止)
itertools.islice(iterable, start, stop[, step]) itertools.islice(可迭代,开始,停止[,步骤])

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. 如果start不为零,则跳过可迭代的元素,直到到达start为止。 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 ; 如果stop为None,则迭代继续进行直到迭代器耗尽为止 otherwise, it stops at the specified position. 否则,它将停在指定位置。 Unlike regular slicing, islice() does not support negative values for start, stop, or step. 与常规切片不同,islice()不支持用于开始,停止或步进的负值。 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). 可用于从内部结构已经展平的数据中提取相关字段(例如,多行报告可能会在每三行列出一个名称字段)。

I think you can just tell it to start at the second line and iterate until the end. 我认为您可以告诉它从第二行开始并进行迭代直到结束。 eg 例如

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

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

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