你好,我对 python 编程相当陌生,我想知道如何修复我的代码,以允许我只在普通文本文档中的两个字符串之间读取。例如,假设我有以下内容
unimportant data
unimportant data
unimportant data
... ... ...
First string #I want to print out starting from this line
Important data
Important data
Important data
Important data
Last String #Last line I dont want to print this line.
unimportant data
unimportant data
unimportant data
unimportant data
unimportant data
unimportant data
到目前为止,我已经能够创建一个简单的文件 I/O 来读取一行。
data_file = open("test.txt", "r")
for line in data_file:
if re.match("(.*)First String(.*)", line):
print(line)
但是这只打印出第一行。
任何提示或帮助将非常感谢。
最佳答案
go = False
start = "First string"
end = "Last String"
with open('path/to/file') as infile:
for line in infile:
line = line.strip()
if line == start: go = True
elif line == end:
go = False
continue
if go: print(line)
如果您只是寻找关键字,而不是匹配整行:
go = False
start = "First string"
end = "Last String"
with open('path/to/file') as infile:
for line in infile:
line = line.strip()
if start in line: go = True
elif end in line:
go = False
continue
if go: print(line)
关于python - 阅读某些单词之间的内容并打印出中间的内容。 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32017495/