在Python中查找字符串并在其后插入文本

时间:2013-12-20 11:00:11

标签: python

我还在学习python。我无法找到特定的字符串并在python中的该字符串后插入多个字符串。我想搜索文件中的行并插入写函数的内容

我尝试过在文件末尾插入的以下内容。

line = '<abc hij kdkd>'
dataFile = open('C:\\Users\\Malik\\Desktop\\release_0.5\\release_0.5\\5075442.xml', 'a')
dataFile.write('<!--Delivery Date: 02/15/2013-->\n<!--XML Script: 1.0.0.1-->\n')
dataFile.close()

4 个答案:

答案 0 :(得分:2)

您可以使用fileinput修改相同的文件并re搜索特定模式

import fileinput,re  

def  modify_file(file_name,pattern,value=""):  
    fh=fileinput.input(file_name,inplace=True)  
    for line in fh:  
        replacement=value + line  
        line=re.sub(pattern,replacement,line)  
        sys.stdout.write(line)  
    fh.close()  

你可以这样调用这个函数:

modify_file("C:\\Users\\Malik\\Desktop\\release_0.5\\release_0.5\\5075442.xml",
            "abc..",
            "!--Delivery Date:")

答案 1 :(得分:1)

这是一个处理文件的建议,我想你搜索的模式是一个整行(线上没有比模式更多的了,模式适合一行)。

line = ... # What to match
input_filepath = ... # input full path
output_filepath = ... # output full path (must be different than input)
with open(input_filepath, "r", encoding=encoding) as fin \
     open(output_filepath, "w", encoding=encoding) as fout:
    pattern_found = False
    for theline in fin:
        # Write input to output unmodified
        fout.write(theline)
        # if you want to get rid of spaces
        theline = theline.strip()
        # Find the matching pattern
        if pattern_found is False and theline == line:
            # Insert extra data in output file
            fout.write(all_data_to_insert)
            pattern_found = True
    # Final check
    if pattern_found is False:
        raise RuntimeError("No data was inserted because line was not found")

此代码适用于Python 3,Python 2可能需要进行一些修改,尤其是with语句(请参阅contextlib.nested。如果您的模式适合一行但不是整行,那么可以使用"theline in line"代替"theline == line"。如果您的模式可以在多行上传播,则需要更强大的算法。:)

要写入同一文件,您可以写入另一个文件,然后将输出文件移到输入文件上。我不打算发布这个代码,但几天前我处于同样的情况。所以这里有一个类,它在两个标签之间的文件中插入内容,并支持在输入文件上写入:https://gist.github.com/Cilyan/8053594

答案 2 :(得分:0)

Python字符串是不可变的,这意味着您实际上不会修改输入字符串 - 您将创建一个新的输入字符串,其中包含输入字符串的第一部分,然后是要插入的文本,然后是其他文本输入字符串。

您可以在Python字符串上使用find方法找到您要查找的文字:

def insertAfter(haystack, needle, newText):
  """ Inserts 'newText' into 'haystack' right after 'needle'. """
  i = haystack.find(needle)
  return haystack[:i + len(needle)] + newText + haystack[i + len(needle):]

您可以像

一样使用它
print insertAfter("Hello World", "lo", " beautiful") # prints 'Hello beautiful world'

答案 3 :(得分:0)

Frerich Raabe ......它对我来说很完美......很好......谢谢!!!

        def insertAfter(haystack, needle, newText):
            #""" Inserts 'newText' into 'haystack' right after 'needle'. """
            i = haystack.find(needle)
            return haystack[:i + len(needle)] + newText + haystack[i + len(needle):]


        with open(sddraft) as f1:   
            tf = open("<path to your file>", 'a+')
            # Read Lines in the file and replace the required content
            for line in f1.readlines():
                build = insertAfter(line, "<string to find in your file>", "<new value to be inserted after the string is found in your file>") # inserts value
                tf.write(build)
            tf.close()
            f1.close()
            shutil.copy("<path to the source file --> tf>", "<path to the destination where tf needs to be copied with the file name>")

希望这有助于某人:)