Possible Duplicate:
Search and replace a line in a file in Python
How do I modify a text file in Python?
I have an input file that I need to rewrite with the different files needed to be modified before running a program. I have tried a variety of the solutions on here but none of them seem to work. I end up just overwriting my file with a blank file
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()
Or with that code for instance the name I am changing is different each time I run the program so I need to replace the entire line not just one keyword
A simple way may be to read the text into a string, then concatenate the string with the text you want to write:
or to change a particular key word:
or to change by line, you can use readlines and refer to each line as the index of a list:
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