2012-07-04 41 views
0

所以希望我没有忽略正确的答案,但... 符合foo栏主题。 如果我有一个看起来像这样的文件:在Python中使用通配符替换文件中的行

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") 
+0

含富... –

+0

为什么FILEOUT字符串这行不通。写(line.replace('',''))而不只是fileout.write(行)? – Gryphius

+0

如果字符串以'食物'开头,应该发生什么? –

回答

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") 
+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='') 
0

其他选项: 如果 “富”,在文本.split() 或者: 如果re.sub(r' FOO \ B”,文本)

1

如果你都OK使用正则表达式和文件可以适合在内存中,然后这应该工作:

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()