Insert text into a text file following specific text using Python

前端 未结 3 1553
没有蜡笔的小新
没有蜡笔的小新 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 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()
    

提交回复
热议问题