tags:

views:

99

answers:

2

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?

A: 

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))
ewall
-1 (1) `line` and each element of `lines` will almost always end with `'\n'` -- why are you adding another one to each line? (2) `with ... in:` -- SyntaxError (`in` is a keyword) (3) `newline` is a brillant name ... try `output_line`
John Machin
Ah, good point... I was thinking that `readline()` stripped the '\n' off the line, as it does in other languages. I guess in that case calling it "newline" is kind of appropriate!
ewall
A: 

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.

Jabir Ali Ouassou