这是我的代码:
Checking = open ("ReadDMI_Out.txt", "rt")
Result = open ("Result.txt", "a")
Fixed = ["T6", "J6", "K6", "N6"]
for line in Checking.readlines():
if (Fixed ["T6", "J6", "K6", "N6"]) in line:
Result.write("1")
else:
print ("0")
答案 0 :(得分:1)
使用re,这就是您正在寻找的简单明了的内容。
import re
infile, outfile = "ReadDMI_Out.txt", "Result.txt"
fixed = ["T6", "J6", "K6", "N6"]
pattern = re.compile('|'.join(fixed))
with open(infile, 'r') as checking:
with open(outfile, 'w') as result:
for line in checking:
result.write(str(int(pattern.search(line))))
还修正了您的空缺情况。您需要关闭它们,除非您使用with open(...) as ...:
作为上下文管理器在完成后自动关闭文件。
此外,您知道您的结果文件中将只有一堆1
吗?您可能需要某种分隔符...
答案 1 :(得分:0)
您似乎想知道(尽管并不完全清楚)文件中的行何时包含["T6", "J6", "K6", "N6"]
中的任何值。
将您的if
测试更改为
if any(f in line for f in Fixed):