Insert text into a text file following specific text using Python

前端 未结 3 1543
没有蜡笔的小新
没有蜡笔的小新 2021-02-10 16:33

I have to edit some text files to include new information, but I will need to insert that information at specific locations in the file based on the surrounding text.

Th

相关标签:
3条回答
  • 2021-02-10 16:51

    If you don't need to work in place, then maybe something like:

    with open("old.txt") as f_old, open("new.txt", "w") as f_new:
        for line in f_old:
            f_new.write(line)
            if 'identifier' in line:
                f_new.write("extra stuff\n")
    

    (or, to be Python-2.5 compatible):

    f_old = open("old.txt")
    f_new = open("new.txt", "w")
    
    for line in f_old:
        f_new.write(line)
        if 'identifier' in line:
            f_new.write("extra stuff\n")
    
    f_old.close()
    f_new.close()
    

    which turns

    >>> !cat old.txt
    a
    b
    c
    d identifier
    e
    

    into

    >>> !cat new.txt
    a
    b
    c
    d identifier
    extra stuff
    e
    

    (Usual warning about using 'string1' in 'string2': 'name' in 'enamel' is True, 'hello' in 'Othello' is True, etc., but obviously you can make the condition arbitrarily complicated.)

    0 讨论(0)
  • 2021-02-10 16:56

    You could use a regex and then replace the text.

    import re
    c = "This is a file's contents, apparently you want to insert text"
    re.sub('text', 'text here', c)
    print c
    

    returns "This is a file's contents, apparently you want to insert text here"

    Not sure if it'll work for your usecase but it's nice and simple if it fits.

    0 讨论(0)
  • 2021-02-10 17:02

    This will look for any string, in the file (not specific, to be at the start of the line only, i.e. can exist spread over multiple lines as well).

    Typically you can follow the algo as:

    1. lookup for the string in the file, and capture "location"
    2. then split the file about this "location", and attempt to create new files as
      • write start-to-loc content to new file
      • next, write your "NEW TEXT" to the new file
      • next, loc-to-end content to new file

    Let us see code:

    #!/usr/bin/python
    
    import os
    
    SEARCH_WORD = 'search_text_here'
    file_name = 'sample.txt'
    add_text = 'my_new_text_here'
    
    final_loc=-1
    with open(file_name, 'rb') as file:
            fsize =  os.path.getsize(file_name)
            bsize = fsize
            word_len = len(SEARCH_WORD)
            while True:
                    found = 0
                    pr = file.read(bsize)
                    pf = pr.find(SEARCH_WORD)
                    if pf > -1:
                            found = 1
                            pos_dec = file.tell() - (bsize - pf)
                            file.seek(pos_dec + word_len)
                            bsize = fsize - file.tell()
                    if file.tell() < fsize:
                                    seek = file.tell() - word_len + 1
                                    file.seek(seek)
                                    if 1==found:
                                            final_loc = seek
                                            print "loc: "+str(final_loc)
                    else:
                                    break
    
    # create file with doxygen comments
    f_old = open(file_name,'r+')
    f_new = open("new.txt", "w")
    f_old.seek(0)
    fStr = str(f_old.read())
    f_new.write(fStr[:final_loc-1]);
    f_new.write(add_text);
    f_new.write(fStr[final_loc-1:])
    f_new.close()
    f_old.close()
    
    0 讨论(0)
提交回复
热议问题