How Do I Append A String To A Line In The Middle Of A File Using Python?
Solution 1:
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'withopen('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
Solution 2:
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.
Post a Comment for "How Do I Append A String To A Line In The Middle Of A File Using Python?"