Python - Write To Beginning and End of Every Line in TXT

Dustin picture Dustin · Oct 28, 2011 · Viewed 11.2k times · Source

I'm currently looking for a way to write to beginning and end of every line of a TXT file in Python. For example,

Current TXT document:

Jimmy
Was
Here

Write the 1st VALUE to the beginning of every line

111Jimmy
111Was
111Here

Write the 2nd VALUE to the end of every line

111Jimmy222
111Was222
111Here222

Can't seem to find anything on Google that describes how to properly have this done. I've found methods of writing to specific lines, but not all of them in this way. Any help is appreciated! Thanks!

Answer

Steven Rumbalski picture Steven Rumbalski · Oct 28, 2011
prefix = '111'
suffix = '222'

with open('source.txt', 'r') as src:
    with open('dest.txt', 'w') as dest:
       for line in src:
           dest.write('%s%s%s\n' % (prefix, line.rstrip('\n'), suffix))