Wan*_*wei 31 python text insert
我有一个文本文件,如下所示:
blah blah
foo1 bar1
foo1 bar2
foo1 bar3
foo2 bar4
foo2 bar5
blah blah
Run Code Online (Sandbox Code Playgroud)
现在我想'foo bar'在'foo1 bar3'和之间插入'foo2 bar4'.
我就这样做了:
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)
Run Code Online (Sandbox Code Playgroud)
这对我有用,但看起来很难看.
Ale*_*lli 57
在Python中对文件进行"伪就地"更改的最佳方法是使用fileinput标准库中的模块:
import fileinput
processing_foo1s = False
for line in fileinput.input('1.txt', inplace=1):
if line.startswith('foo1'):
processing_foo1s = True
else:
if processing_foo1s:
print 'foo bar'
processing_foo1s = False
print line,
Run Code Online (Sandbox Code Playgroud)
如果要保留旧版本,也可以指定备份扩展,但这与代码的工作方式相同 - .bak用作备份扩展,但也会在更改成功完成后将其删除.
除了使用正确的标准库模块之外,这段代码使用更简单的逻辑:"foo bar"在每行开始后插入一行foo1,你需要一个布尔值(我是否在这样的运行里面?)并且有问题的bool可以是根据当前行是否以这种方式开始无条件地设置.如果你想要的精确逻辑与这个逻辑略有不同(这是我从你的代码中推断出来的),那么相应地调整这个代码应该不难.
小智 12
改编Alex Martelli的例子:
import fileinput
for line in fileinput.input('1.txt', inplace=1):
print line,
if line.startswith('foo1 bar3'):
print 'foo bar'
Run Code Online (Sandbox Code Playgroud)
回想一下,迭代器是一流的对象.它可以在多个使用的语句.
这是一种处理这个问题的方法,没有很多复杂的if语句和标志.
with open(tmptxt, 'w') as outfile:
with open(txt, 'r') as infile:
rowIter= iter(infile)
for row in rowIter:
if row.startswith('foo2'): # Start of next section
break
print row.rstrip(), repr(row)
print "foo bar"
print row
for row in rowIter:
print row.rstrip()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
54214 次 |
| 最近记录: |