A simple way may be to read the text into a string, then concatenate the string with the text you want to write:
infile = open('hey.txt','r+') content = infile.read() text = ['foo','bar'] for item in text: content +=item #adds 'foo' on first iteration, 'bar' on second infile.write(content) infile.close()
or to change a particular key word:
infile = open('hey.txt','r+') content = infile.read() table = str.maketrans('foo','bar') content = content.translate(table) #replaces 'foo' with 'bar' infile.write(content) infile.close()
or to change by line, you can use readlines and refer to each line as the index of a list:
infile = open('hey.txt','r+') content = infile.readlines() #reads line by line and out puts a list of each line content[1] = 'This is a new line\n' #replaces content of the 2nd line (index 1) infile.write(content) infile.close()
Maybe not a particularly elegant way to solve the problem, but it could be wrapped up in a function and the 'text' variable could be a number of data types like a dictionary, list, etc. There are also a number of ways to replace each line in a file, it just depends on what the criteria are for changing the line (are you searching for a character or word in the line? Are you just looking to replace a line based on where it is in the file?)--so those are also some things to consider.
Edit: Added quotes to third code sample