使用python查找并替换多个文档中多行的一部分?

时间:2013-08-01 12:25:35

标签: python string replace

我正在尝试使用python替换多个乳胶文档中的几行部分。这就是我所做的:

import fileinput, glob, string, sys, os
from os.path import join

def search_rep(path,search,replace):


# replace a string in multiple files


    files = glob.glob(path)

    for file in files:
        if os.path.isfile(file):
            for line in file.splitlines(): # or whatever arbitrary loop
                if line.find(search) > -1:
                    print "Replacing" + replace + "on line: %s" % line
                    line.replace(search, replace)



def main():

    path = "/home/stig/test/*.tex"
    search = "/home/stig/hfag/oppgave/figs_plots/"
    replace = "/home/stig/forskning_linux/oppgave_hf2/figs_plots/"
    search_rep(path,search,replace)

if __name__ == "__main__":
    sys.exit(main())  

但脚本不会更改文件中的任何内容。怎么了?

谢谢

Stig

1 个答案:

答案 0 :(得分:1)

考虑使用fileinput module。它非常适合这个问题。 Example

import fileinput
import glob
import sys

path = "/home/stig/test/*.tex"
search = "/home/stig/hfag/oppgave/figs_plots/"
replace = "/home/stig/forskning_linux/oppgave_hf2/figs_plots/"

for line in fileinput.input(glob.glob(path), inplace=1):
    sys.stdout.write(line.replace(search, replace))

另请参阅inplacebackup参数,这些参数允许您进行替换(如果出现错误,则备份安全)。