本文介绍了使用python文件输入模块跳过第一行的优雅方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 python fileinput模块时,是否有跳过第一行文件的优雅方式?



数据文件有很好的格式化数据,但第一行是标题。使用 fileinput 如果行看起来不包含数据,我将不得不包含检查和放弃行。



问题在于它会对文件的其余部分应用相同的检查。
使用 read()可以打开文件,读取第一行然后循环遍历文件的其余部分。是否有类似的技巧与 fileinput



有没有一个优雅的方式来跳过第一行的处理?

示例代码:

 导入文件输入

#如何优雅地跳过第一行?

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


解决方案

c $ c> fileinput 模块包含了一堆方便的函数,其中一个似乎正在做你想要的:

<$ p $如果不是fileinput.isfirstline():
data = proces_line(line);如果不是fileinput.isfirstline():
,那么在fileinput.input([file.dat])
输出(数据)


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

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

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?

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)
解决方案

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

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

fileinput module documentation

这篇关于使用python文件输入模块跳过第一行的优雅方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-20 22:18