4

I'm currently looking for a way to write to the beginning and end of every line of a text 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.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Dustin
  • 6,207
  • 19
  • 61
  • 93

4 Answers4

12
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))
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
5

You can make changes to the file without opening multiple files by using fileinput with inplace=1:

import fileinput
for line in fileinput.input('test.txt', inplace=1):
    print '{0}{1}{2}'.format('111', line.rstrip('\n'), '222')
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
0

Assuming you have read the file using readlines() in a list you can do

value1 = "" # appended at first
value2 = "" # appended at last
data = file.readlines()
data = [ ( value1 + str.rstrip('\n') + value2 + "\n" ) for str in data ]

and then write data back to the file....

user671805
  • 602
  • 1
  • 12
  • 29
-1
f1o = open("input.txt", "r")
f2o = open("output.txt", "w")

for line in f1o:
    f2o.write("111%s222\n" % line.replace("\n"))

f1o.close()
f2o.close()
lifeisstillgood
  • 3,265
  • 2
  • 21
  • 22