Possible Duplicate:
How do I modify program files in Python?
I need to insert some text at the beginnnig and the end of each line of a text file. how can I use python to do this?
Possible Duplicate:
How do I modify program files in Python?
I need to insert some text at the beginnnig and the end of each line of a text file. how can I use python to do this?
First, open the input and output files...
infile = open('inputfile', 'r')
outfile = open('outputfile', 'w')
...then loop thru the lines...
for line in infile:
...add your content at the beginning...
newline = "stuff for beginning of line" + line
...then write the line to the output...
outfile.write(newline)
...lastly, don't forget to close your files!
infile.close()
outfile.close()
Or, here's a shorter version that is more "Pythonic". (Note that it sucks in the whole file at once, so don't use it for really large files, or it will suck!):
with open('inputfile', 'r') as infile:
lines = infile.readlines()
with open('outputfile', 'w') as outfile:
outfile.write("prefix-" + "prefix-".join(lines))
Unless you perform this particular task on a regular basis, you don't really need a python script for it. Most editors created with programming in mind (Vim, Emacs, Notepad++, etc) supports some kind of regexp-based search and replace.
Replacing ^\(.*\)$ with "\1" should wrap all lines in double-quotes in editors that use simple regular expressions. Depending on what tool you use, this might be done in easier ways too; e.g. in a line-by-line substitution with Sed or Vim, replacing .* with "&" does the same job.
If you're unfamiliar with regular expressions, I highly recommend googling for a good tutorial. Check out the three-part introduction to Sed by Daniel Robbins if you're using Linux/Unix. You may also refer to this page for a more general introduction to regular expressions.