【发布时间】:2018-11-26 15:23:07
【问题描述】:
我有 2 个文件,看起来像: 第一:
port2
port4
port10
etc.
第二:
port1
some stuff
about the port
I do not need
!
port2
some stuff
about the port
I really need
!
some generic stuff which is completely useless
!
port3
some stuff
about the port
I do not need
!
port4
some stuff
about the port
I really need
!
etc
现在,我想要创建一个循环,对于第一个文档中的每一行,我们将遍历第二个文档并创建一个包含我需要的所有数据的新文件(“port2”直到“!”, "port4" 直到 "!" 等)
到目前为止我得到了什么:
def access():
with open ("D:/portlist.txt") as f1, open ("D:/config.txt") as f2:
match = False
for line in f1:
newConfig = open ("D:/portconfig.test.txt", "a")
interface = line
for line2 in f2:
if re.match(interface, line2):
newConfig.write(line2)
print(line2)
match = True
elif re.match("!", line2):
match = False
elif match:
newConfig.write(line2)
newConfig.close()
access()
问题是脚本在返回所有关于 port2 后停止。似乎脚本没有返回到第一个循环以继续该过程。 有什么想法吗?
【问题讨论】:
-
欢迎来到 StackOverflow。如果您从这两个示例输入文件中向我们展示所需的输出文件,将对我们有很大帮助。否则,你的问题很好。见How to create a Minimal, Complete, and Verifiable example。
标签: python loops for-loop if-statement