Я пытаюсь добавить несколько строк в файл (input.txt) и заменить несколько строк в одном файле (input.txt), но мой код вставляет только строки в конец файла. Знаете ли вы, как я могу исправить код, чтобы получить ожидаемый выходной файл, который я хочу?
Мой код:
import re
searchtext1 = """
AB 3.483e-01 2.52e-02 ; 3.46 0.0123
"""
# add these lines after searchtext1
addtext1 = """
CD 2.123e-01 1.31e-02 ; 7.25 0.0145
DE 4.896e-01 7.25e-02 ; 8.25 0.0185
"""
searchtext2 = """
; atom
#atomnumber
#molecule
[weight]
"""
# replace these lines to searchtext2
changetext2 = """
; iron
#48kcal
35 mol
#12 g
"""
with open('input.txt', 'ab+') as infile:
matches1 = re.findall(r'^(\d+)\.(.*)$', searchtext1, re.MULTILINE)
infile.write(addtext1)
matches2 = re.findall(r'^(\d+)\.(.*)$', searchtext2, re.MULTILINE)
infile.write(changetext2)
input.txt:
[atom]
123
[bonds]
XY 4.212e-01 4.18e-02 ; 8.01 0.0487
AB 3.483e-01 2.52e-02 ; 3.46 0.0123
[molecule]
1 2
3 4
TY 0.412e-01 1.72e-02 ; 0.32 0.0455
; atom
#atomnumber
#molecule
[weight]
calculated value is 5 kcal/mol
end file
ожидаемый выходной файл:
[atom]
123
[bonds]
XY 4.212e-01 4.18e-02 ; 8.01 0.0487
AB 3.483e-01 2.52e-02 ; 3.46 0.0123
CD 2.123e-01 1.31e-02 ; 7.25 0.0145
DE 4.896e-01 7.25e-02 ; 8.25 0.0185
[molecule]
1 2
3 4
TY 0.412e-01 1.72e-02 ; 0.32 0.0455
; iron
#48kcal
35 mol
#12 g
calculated value is 5 kcal/mol
end file