0

我正在尝试使用 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())  

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

谢谢

斯蒂格

4

1 回答 1

1

考虑使用fileinput模块。它非常适合这个问题。示例

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参数,它允许您在原地进行替换(在发生错误的情况下安全备份)。

于 2013-08-01T12:42:55.800 回答