Input:
ID information1
Aa information1-1
CC information1-2
Ca Homo sapiens
Da information1-4
//
ID information2
Aa information2-1
CC information2-2
Ca information2-3
Da information2-4
//
Expected output:
ID information1
Aa information1-1
Ca Homo sapiens
Da information1-4
//
Code1:
# Step1
with open(input_file, 'r') as input, open('temp.txt', 'w') as temp:
for line in input:
if not line.startswith('CC '):
temp.write(line)
Code2:
# Step2
word = 'Homo sapiens'
with open('temp.txt', 'r') as input, open(output_file, 'w') as output:
for block in input.read().split('//'):
if word in block:
output.write(block)
output.write('//')
I want to proceed with two steps within one code, not two separate codes. Is there any suggestion for me?!
CodePudding user response:
You can do this in one pass by building a "block" of potential output lines as you read the input line by line. Consider this:
word = 'Homo sapiens'
infile = 'blockin.txt'
outfile = 'blockout.txt'
with open(infile) as txtin, open(outfile, 'w') as txtout:
block = []
useblock = False
for line in txtin:
if line.startswith('//'):
if useblock:
block.append(line)
txtout.write(''.join(block))
useblock = False
block = []
elif not line.startswith('CC '):
block.append(line)
if not useblock and word in line:
useblock = True