我有一个文本,我打印了每一行。
每次读取的行都是标志时,我想停止(第一次打印“ flag!”,第二次停止)文本
但它不会停止
代码部分:
import sys
path = "/somepath/story_line"
flag = "010001"
def process(line):
sys.stdout.write(line)
sys.stdout.flush()
time.sleep(2.4)
line = fileIN.readline()
with open(path, "r") as content:
if line != flag:
for line in content:
process(line)
if line == path:
print ("flag")
文本部分
[START]
010001
welcome traveler,
This story begins in a dark era where Evil took over the weak... Many times ago a dark force came from beyond the sky and over*** the balance of this land.
You are the hope and new strengh of this world, please choose wisely
....
....
Let the story begin
[END]
010001
GAME OVER !!!
我是python的新手,我尝试了子处理或将每行追加到列表中以解析列表,但无济于事。 有人可以减轻这个压力吗?
答案 0 :(得分:0)
您的问题是python传递变量的方式。在函数process(line)
的结尾,您要做
line = fileIN.readline()
但是,此仅在当前范围内修改line
。退出该功能后,所做的更改就会丢失。
解决方案是,只需在函数结尾处分配给line
,就可以
return fileIN.readline()
,然后在下面替换行
process(line)
使用
line = process(line)
答案 1 :(得分:0)
我不确定我是否理解问题和代码,似乎您正在尝试多次读取文件中的行?
使用“打开”功能,您可以自由迭代结果,即逐行读取。
这就是我会怎么做你所描述的
import sys
import time
path = "/path/to/my/file"
flag = "010001"
def process(line):
if line.strip() == flag:
process.flagcount += 1
if process.flagcount == 1:
sys.stdout.write("flag!\n")
return process.flagcount
sys.stdout.write(line)
time.sleep(2.4)
return 0
process.flagcount = 0 #initialise a static counting attribute inside process()
#open the file
with open(path, "r") as content:
#read each line
for line in content:
#process it and if it tells us it's counted more than one flag then stop reading.
if process(line) > 1:
break