读取 Python 文件中的行时跳过前几行 [英] Skip first couple of lines while reading lines in Python file
本文介绍了读取 Python 文件中的行时跳过前几行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在阅读文本文件时跳过前 17 行.
假设文件如下所示:
<预><代码>00000000000000000好东西我只想要好东西.我正在做的事情要复杂得多,但这是我遇到麻烦的部分.
解决方案
使用切片,如下所示:
with open('yourfile.txt') as f:lines_after_17 = f.readlines()[17:]
<小时>
如果文件太大而无法加载到内存中:
with open('yourfile.txt') as f:对于 _ 范围(17):下一个(f)对于 f 中的行:# 做东西
I want to skip the first 17 lines while reading a text file.
Let's say the file looks like:
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
good stuff
I just want the good stuff. What I'm doing is a lot more complicated, but this is the part I'm having trouble with.
解决方案
Use a slice, like below:
with open('yourfile.txt') as f:
lines_after_17 = f.readlines()[17:]
If the file is too big to load in memory:
with open('yourfile.txt') as f:
for _ in range(17):
next(f)
for line in f:
# do stuff
这篇关于读取 Python 文件中的行时跳过前几行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文