Tôi có một tập tin văn bản mà trông như thế này:Chèn dòng tại vị trí xác định của một Text File
blah blah
foo1 bar1
foo1 bar2
foo1 bar3
foo2 bar4
foo2 bar5
blah blah
Bây giờ tôi muốn chèn 'foo bar'
giữa 'foo1 bar3'
và 'foo2 bar4'
.
Đây là cách tôi đã làm nó:
import shutil
txt = '1.txt'
tmptxt = '1.txt.tmp'
with open(tmptxt, 'w') as outfile:
with open(txt, 'r') as infile:
flag = 0
for line in infile:
if not line.startswith('foo1') and flag == 0:
outfile.write(line)
continue
if line.startswith('foo1') and flag == 0:
flag = 1
outfile.write(line)
continue
if line.startswith('foo1') and flag == 1:
outfile.write(line)
continue
if not line.startswith('foo1') and flag == 1:
outfile.write('foo bar\n')
outfile.write(line)
flag = 2
continue
if not line.startswith('foo1') and flag == 2:
outfile.write(line)
continue
shutil.move(tmptxt, txt)
này làm việc cho tôi, nhưng trông khá xấu xí.
Cảm ơn các cách tiếp cận hoàn toàn khác nhau. –