python 使用python文件输入模块时跳过第一行的优雅方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1523378/
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-11-03 22:28:37  来源:igfitidea点击:

Elegant way to skip first line when using python fileinput module?

pythonfile-io

提问by stefanB

Is there an elegant way of skipping first line of file when using pythonfileinput module?

使用pythonfileinput 模块时,是否有一种优雅的方法可以跳过文件的第一行?

I have data file with nicely formated data but the first line is header. Using fileinputI would have to include check and discard line if the line does not seem to contain data.

我有数据格式很好的数据文件,但第一行是标题。fileinput如果该行似乎不包含数据,则使用I 必须包括检查和丢弃行。

The problem is that it would apply the same check for the rest of the file. With read()you can open file, read first line then go to loop over the rest of the file. Is there similar trick with fileinput?

问题是它会对文件的其余部分应用相同的检查。有了read()你可以打开文件,读取然后第一线去遍历文件的其余部分。有类似的技巧fileinput吗?

Is there an elegant way to skip processing of the first line?

有没有一种优雅的方法来跳过第一行的处理?

Example code:

示例代码:

import fileinput

# how to skip first line elegantly?

for line in fileinput.input(["file.dat"]):
    data = proces_line(line);
    output(data)

回答by nosklo

lines = iter(fileinput.input(["file.dat"]))
next(lines) # extract and discard first line
for line in lines:
    data = proces_line(line)
    output(data)

or use the itertools.islice way if you prefer

或者如果您愿意,可以使用 itertools.islice 方式

import itertools
finput = fileinput.input(["file.dat"])
lines = itertools.islice(finput, 1, None) # cuts off first line
dataset = (process_line(line) for line in lines)
results = [output(data) for data in dataset]

Since everything used are generators and iterators, no intermediate list will be built.

由于使用的一切都是生成器和迭代器,因此不会构建中间列表。

回答by Phil

The fileinputmodule contains a bunch of handy functions, one of which seems to do exactly what you're looking for:

fileinput模块包含一堆方便的功能,其中一个似乎完全符合您的要求:

for line in fileinput.input(["file.dat"]):
  if not fileinput.isfirstline():
    data = proces_line(line);
    output(data)

fileinput module documentation

文件输入模块文档

回答by user3698773

with open(file) as j: #open file as j
    for i in j.readlines()[1:]: #start reading j from second line.