Louise Cullen
Louise Cullen

Reputation: 107

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?

Upvotes: 0

Views: 1568

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195633

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

Upvotes: 2

Rory Daulton
Rory Daulton

Reputation: 22564

Yes, there is a way to do this. Once you find the file, close it. Then open it again and create a new text file. read the input file line by line and write each line to the output file. When you reach the line containing the specified string, append your desired added text to that line when you copy it to the output file. Then copy the rest of the input file to the output file. You may want to keep examining each line--your specified text may be in more than one line.

Note that you cannot just append into the middle of a file. The encoded characters sit is particular places in the file, and they will not just move slightly to add a few more characters in the middle. You almost certainly need to make a new file. Of course, when you are done you could delete the input file and rename the output file.

The only way you could avoid the output file is if there is "blank space" at the end of the target line, where you could overwrite your new text. This is very unlikely to be true, unless it was planned in advance. If it were planned, you could open the input file for writing, seek the proper position, then write your new text which would overwrite any old text at that location.

Upvotes: 0

Related Questions