我有一个文件,格式如下:
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)
for line in iter(fin.readline,''):
代替,.tell()
将再次正确。 :-) - Martijn Pietersitertools.takewhile
和Python 3.3的yield from
会更好... yield from it.takewhile(lambda x: x == 'xxxxx\n' or x == '',fobj)
然后只需yield line1
,如果下一行不等于line2
则重复... - mgilsonit.takewhile
解决这个问题,但由于它只是在文件中进行迭代,所以我意识到ftell()
的不一致性。 - Abhijitstr.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