我有一个文件,它有一些标题行,例如
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:
跳过前5行:
.readlines()
一次性读取文件中的所有数据。第一次通话后没有更多的行要读了。在您可能想使用
.readline()
(nos
,单数)来代替:请注意,因为
^{2}$.readlines()
已经返回了一个列表,所以不需要遍历这些项。您也可以使用.read()
读取文件的其余部分:或者,将file对象视为iterable,并使用^{} 切片iterable来跳过前五行:
这确实会产生行,而不是一个大字符串,但是如果要逐行处理输入文件,那么通常最好还是这样。可以直接在切片和句柄行上循环:
不要混合使用file对象作为iterable和
.readline()
;由file对象实现的迭代协议使用一个内部缓冲区来确保.readline()
所不知道的效率;在迭代之后使用.readline()
很可能会在文件中返回比预期更远的数据。在相关问题 更多 >
编程相关推荐