0

所以希望我没有忽略正确的答案,但是......与 foo bar 主题保持一致。如果我有一个看起来像这样的文件:

blah boo who
bar blah blah
bar blah blah
foo some other chars
bar blah
black sheep

我希望能够在不知道以下内容的情况下替换以或包含开头的行'foo'并替换整行。

我当前的代码很讨厌但可以工作,有没有办法在不加载文件和循环的情况下做到这一点?或者至少比这更有效?

filein = open("file", "r")
fileout = open("file.tmp", "w")
for line in filein:
    if line.startswith("foo"):
        fileout.write( "foo"+"my new numbers")
    else:
        fileout.write( line.replace('', '') )
filein.close()
fileout.close()
os.rename("file.tmp", "file")
4

4 回答 4

1
from fileinput import FileInput
with FileInput(files="file", inplace=True) as f:
    for line in f:
        if "foo" in line:
            line = "foo"+"my new numbers"+"\n"
        print(line, end='')
于 2012-07-04T11:20:38.307 回答
1

如果您对正则表达式没问题并且文件可以放入内存,那么这应该可以工作:

file = open("file", "r")
data = file.read()
file.close()
data = re.sub(re.compile("^(.*)(foo)(.*)$",re.MULTILINE),'foo my new numbers',data)
file = open("file1", "w")
file.write(data)
file.close()
于 2012-07-04T12:19:52.130 回答
0

更短的代码可以是:

import os
with open('file') as f1,open('file.tmp','w') as f2:
    lines=[x if 'foo' not in x.split() else "foo my new numbers\n" for x in f1]
    f2.writelines(lines)
os.rename("file.tmp", "file")           

或者如果文件很大:

import os
with open('data1.txt') as f1,open('file.tmp','w') as f2:
    for x in f1:
        if 'foo' in x.split():
            f2.write("foo my new numbers\n")
        else:
            f2.write(x)
os.rename("file.tmp", "file") 
于 2012-07-04T11:17:51.723 回答
0

其他选项:如果 text.split() 中的 "foo" 或者:如果 re.sub(r'foo\b', text)

于 2012-07-04T11:30:19.373 回答