私はフォーマットとしてファイルを持っています:
xxxxx
yyyyy
zzzzz
ttttt
そして、xxxxx 行と yyyyy 行の間のファイルに次のように書き込む必要があります。
xxxxx
my_line
yyyyyy
zzzzz
ttttt
私はフォーマットとしてファイルを持っています:
xxxxx
yyyyy
zzzzz
ttttt
そして、xxxxx 行と yyyyy 行の間のファイルに次のように書き込む必要があります。
xxxxx
my_line
yyyyyy
zzzzz
ttttt
with open('input') as fin, open('output','w') as fout:
for line in fin:
fout.write(line)
if line == 'xxxxx\n':
next_line = next(fin)
if next_line == 'yyyyy\n':
fout.write('my_line\n')
fout.write(next_line)
これにより、ファイル内のすべてのxxxxx\n
との間に行が挿入yyyyy\n
されます。
別のアプローチとして、xxxxx\nyyyyy\n
def getlines(fobj,line1,line2):
for line in iter(fobj.readline,''): #This is necessary to get `fobj.tell` to work
yield line
if line == line1:
pos = fobj.tell()
next_line = next(fobj):
fobj.seek(pos)
if next_line == line2:
return
次に、に直接渡されたこれを使用できますwritelines
。
with open('input') as fin, open('output','w') as fout:
fout.writelines(getlines(fin,'xxxxx\n','yyyyy\n'))
fout.write('my_line\n')
fout.writelines(fin)
ファイルが小さい場合は、次のように簡単に使用できますstr.replace()
。
>>> !cat abc.txt
xxxxx
yyyyy
zzzzz
ttttt
>>> with open("abc.txt") as f,open("out.txt",'w') as o:
data=f.read()
data=data.replace("xxxxx\nyyyyy","xxxxx\nyourline\nyyyyy")
o.write(data)
....:
>>> !cat out.txt
xxxxx
yourline
yyyyy
zzzzz
ttttt
巨大なファイルの場合、mgilson のアプローチを使用します。