所以希望我没有忽略正确的答案,但... 符合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")
含富... –
为什么FILEOUT字符串这行不通。写(line.replace('',''))而不只是fileout.write(行)? – Gryphius
如果字符串以'食物'开头,应该发生什么? –