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

2024-07-04 08:18:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python替换多个latex文档中的几行代码。这就是我所做的:

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

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

谢谢

斯蒂格


Tags: pathinimporthomesearchstringifos
1条回答
网友
1楼 · 发布于 2024-07-04 08:18:10

考虑使用^{} 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参数,这两个参数允许您就地进行替换(在发生错误时具有备份的安全性)。在

相关问题 更多 >

    热门问题