with open("test.txt") as f:
for line in f:
if line.rstrip() == "***a":
print("")
for line in f:
if line.rstrip() == " -a":
break
print(line.rstrip())
用于:
^{pr2}$
将输出:
foo bar
lorem ipsum
dolor
bar bar
foobar
foob
如果您想要没有换行符的行,我们可以map将其关闭,然后继续逐行迭代:
with open("test.txt") as f:
# itertools.imap python2
f = map(str.rstrip, f)
for line in f:
if line == "***a":
print("")
for line in f:
if line == " -a":
break
print(line)
def printlines():
# this is our state
isWithin = False
with open('text.txt') as f:
for line in f:
# Since the line contains the line breaking character,
# we have to remove that first
line = line.rstrip()
# check for the patterns to change the state
if line == "***a":
isWithin = True
elif line == " -a":
isWithin = False
# check whether we’re within our state
elif isWithin:
print line
如果多次出现,则可以在到达起始线时启动内部循环,这相当于while尝试执行的操作:
用于:
^{pr2}$将输出:
如果您想要没有换行符的行,我们可以
map
将其关闭,然后继续逐行迭代:使用break和continue:
中断
继续
使用状态机。这意味着,一旦你看到你的开场白,就要设置一个状态,这样你就知道下面几行与你有关了。然后继续寻找结束模式来关闭它:
因为我们只在}而不输出其他内容:
^{pr2}$isWithin
状态下打印,所以我们可以很容易地跳过***a
/-a
模式之外的任何部分。因此,处理以下文件将正确地输出Hello
和{另外,您应该使用
with
语句打开文件,并直接迭代file对象,而不是读取它并调用splitlines()
。这样可以确保文件被正确地关闭,并且只读取一行又一行的内容,从而提高内存效率。在相关问题 更多 >
编程相关推荐