Search code examples
pythonstringappendtext-filesline

How do I append a string to a line in the middle of a file using python?


I want to be able to open a file, locate a specific string and then append a string to that specific line.

So far, I have:

import errno
import glob

path = '/path/to/key_files/*.txt'
SubjectName = 'predetermined'

files = glob.glob(path)
for filename in files:
    try:
        with open(filename, 'r+') as f:
           for line in f:
               if SubjectName in line:
                   print(line)
    except IOError as exc:
        if exc.errno != errno.EISDIR:
            raise

Which prints a line from the text file containing the string I specified, so I know all the code works in terms of locating the correct line. I now want to add the string ',--processed\n' to the end of the located line, as opposed to appending it to the very end of the file. Is there a way to do this?


Solution

  • You can use re.sub. After reading the file with f.read() you can use see f.seek(0) to rewind to the beginning and use f.write() to write your new content (you need to open the file with r+ flag):

    Content of the file.txt:

    Line1
    Line2
    Line3
    Line4
    

    Script:

    import re
    
    SubjectName = 'Line3'
    
    with open('file.txt', 'r+') as f:
        s = f.read()
        new_s = re.sub(r'^(.*{}.*)$'.format(re.escape(SubjectName)), lambda g: g.group(0) + ',--processed', s, flags=re.MULTILINE)
        f.seek(0)
        f.write(new_s)
    

    Afer running the file.txt contains:

    Line1
    Line2
    Line3,--processed
    Line4