在Python中读取文件时忽略行
程序的第一部分要求我读入文件,但忽略前几行。我在中读取的文件如下所示:在Python中读取文件时忽略行,python,readline,Python,Readline,程序的第一部分要求我读入文件,但忽略前几行。我在中读取的文件如下所示: Blah Blah Blah some character(%% for example) More Blah. 我的问题是,我如何读取文件中的所有行,而忽略%%及其上方的每一行?只需读取并转储行,直到找到所需的行为止。文件迭代器执行内部缓冲,因此您可以根据以后要执行的操作进行不同的操作 with open('somefile') as f: # ignore up to the first line with "
Blah
Blah
Blah
some character(%% for example)
More Blah.
我的问题是,我如何读取文件中的所有行,而忽略%%及其上方的每一行?只需读取并转储行,直到找到所需的行为止。文件迭代器执行内部缓冲,因此您可以根据以后要执行的操作进行不同的操作
with open('somefile') as f:
# ignore up to the first line with "%%"
for line in f:
if "%%" in line:
break
# then process the rest
for line in f:
do_amazing_stuff(line)
或许
with open('somefile') as f:
# ignore up to the first line with "%%"
while True:
line = f.readline()
if not line or "%%" in line:
break
# then process the rest
do_amazing_stuff(f.read())
您可以使用标志:
with open('myfile.txt') as fd:
skip = True
for line in fd:
if line.startswith("*"): skip = False
if not skip:
# process line
您可以使用iter的两个参数版本:
with open('iter.txt') as f:
for line in iter(f.readline, '%%\n'):
# for line in iter(lambda: f.readline().startswith('%%'), True):
# for line in iter(lambda: '%%' in f.readline(), True):
pass
for line in f:
print line,
这将迭代,直到第一个参数(函数)返回的值不等于第二个参数
with open('iter.txt') as f:
for line in iter(f.readline, '%%\n'):
# for line in iter(lambda: f.readline().startswith('%%'), True):
# for line in iter(lambda: '%%' in f.readline(), True):
pass
for line in f:
print line,