在Python中使用通配符替换文件中的一行

时间:2012-07-04 11:07:29

标签: python

所以希望我没有忽略正确的答案,但...... 与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") 的行,并在不知道以下内容的情况下替换整行。

我当前的代码很讨厌但有效,有没有办法在不加载文件的情况下进行循环?或至少比这更有效率?

{{1}}

4 个答案:

答案 0 :(得分: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='')

答案 1 :(得分: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()

答案 2 :(得分: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") 

答案 3 :(得分:0)

其他选择:      如果text.split()中的“foo” 要么:     if re.sub(r'foo \ b',text)