bar*_*arp 6 python io python-2.7
我有一个文件格式:
xxxxx
yyyyy
zzzzz
ttttt
Run Code Online (Sandbox Code Playgroud)
我需要在 xxxxx 和 yyyyy 行之间的文件中写入:
xxxxx
my_line
yyyyyy
zzzzz
ttttt
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
这将在文件中每次出现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
Run Code Online (Sandbox Code Playgroud)
然后你可以使用它直接传递到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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22556 次 |
| 最近记录: |