Python在StringIO缓冲区中搜索和替换?

时间:2011-11-21 13:36:16

标签: python

我正在使用telnetlib来获取几行文字(tn = telnetlib)。

o = cStringIO.StringIO(tn.read_all())

# this prints the entire text as it should (a few lines)
print o.getvalue()
o.close()

现在,有没有办法基于字符串进行搜索,如果找到字符串,则替换cStringIO缓冲区中的整行? 我用磁盘上的文件做了这个,但它不是很有条理。代码很乱,我需要大量的临时文件,我需要进行大量的搜索和替换操作。

2 个答案:

答案 0 :(得分:1)

对字符串进行搜索和替换,然后在需要时将结果放入StringIO缓冲区:

lines = tn.read_all().splitlines()
for i, line in enumerate(lines):
    if search_string in line:
        lines[i] = replacement_string
o = cStringIO.StringIO("\n".join(lines))

答案 1 :(得分:1)

@Sven Marnach回答的小变种:

from cStringIO import StringIO
lines = tn.read_all().splitlines(True) # keep \n
o = StringIO()
for line in lines:
    if search_string in line:
        line = replacement_string # or line = line.replace(search_string, new_string) 
    o.write(line)