我正在尝试提取一些行,直到我从.txt文件中获取关键字来声明带有文本的变量。现在我有这个代码来获取我想要的行:
def extract_line(row):
a = open("Z:/xyz/xyz/test.txt","r", encoding="utf-8")
b = a.readlines()
a.close()
count = 0
for line in b:
count += 1
if count == row:
if "REQUIREMENT TYPE " in line:
break
else:
print(line)
extract_line(row + 1)
它可以很好地打印出行,但我无法提取行来声明带有文本的变量。我怎么做?
我不确定你为什么要递归地调用这个函数。
如果我的问题是正确的,那么您希望存储直到达到某个关键字的行。一旦你点击关键字,你想要破解,你需要一个变量来拥有你读过的那一行。
您可以使用以下代码执行此操作:
with open("file.txt", "r") as f:
extracted_line = [] # create an empty list to store the extracted lines
for line in f:
if 'REQUIREMENT TYPE' in line: # if keyword is present in the current line, break
break
else:
extracted_line.append(line) # else, append the line to store them later
stored_lines = ''.join(extracted_line) # variable which stores the lines till keyword
print stored_lines
f.close()
我在代码旁边放了评论。希望这能回答你的问题。如果您需要任何澄清,请告诉我。