我需要在文件中搜索一些字符串,然后将其中的内容复制到一个单独的文件中。
例如'Hello'在文件中重复多次。我想将这些后续“Hello”中的文本复制到文件中。每次“Hello”重复文本后,需要转到新文件。
请确认我在以下脚本中使用的逻辑是否正确,以及它是否从我的'If'循环中给出了缩进错误。
import re
text_file = "Hello.txt"
search1 = "Hello"
outfile = "charlie"
write1 = False
x = 0
with open(text_file , "r") as infile:
fi = infile.readlines()
with open("outfile%s" % x, "w") as fo:
fo.write("============================================ \n")
for line in fi:
if search1 in line:
write1 = True
x +=1
fo.write(line)
elif write1:
fo.write(line)
答案 0 :(得分:2)
试试这个
text_file = 'Hello.txt'
search_key = 'Hello'
out_file = 'charlie_%d.txt'
current_file = None
occurrence = 0
with open(text_file, 'r') as input_file:
try:
for src_line in input_file:
if search_key in src_line:
# searched text is found, writing to file
occurrence += 1
if current_file:
current_file.close()
current_file = open(out_file % occurrence, 'w')
current_file.write("============================================ \n")
current_file.write(src_line)
elif current_file:
# no searched text, write line to already open file
current_file.write(src_line)
finally:
if current_file:
current_file.close()