简体   繁体   English

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

[英]Find and replace a part of several lines in multiple documents using python?

I'm trying to replace parts of several lines in multiple latex documents using python. 我正在尝试使用python替换多个乳胶文档中的几行内容。 This is what I've done: 这是我所做的:

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

But the script doesn't change anything in the files. 但是该脚本不会更改文件中的任何内容。 What's wrong? 怎么了?

Thanks 谢谢

Stig 斯蒂格

Consider using the fileinput module . 考虑使用fileinput模块 It's a good fit for this problem. 非常适合此问题。 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))

See also the inplace and backup parameters, which allow you to do the replacement in place (with the safety of backup in case of a mistake). 另请参阅inplacebackup参数,这些参数使您可以inplace进行替换(在发生错误的情况下使用备份的安全性)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM