Re: String replacements

Ken Manheimer (klm@NIST.GOV)
Wed, 29 Mar 1995 17:05:14 -0500 (EST)

On Wed, 29 Mar 1995, Glen Collins wrote:

> I am using python in a UNIX environment to read in shell scripts and
> modify them using python. Some of the file contain echo statments which
> have to include "\n" in them. What I would like to be able to do is
> read them in and write them back out. But python seems to change these
> into their proper value when written. In other words I get a carriage
> return in the actual resulting file and not a "\n". Sample:

I'm a bit surprised by the problem, and suspect that you may be making
things more difficult for yourself than necessary.

How are you reading the file? The file-object 'readline' method takes
care of backslashes properly (duplicating them on encountering them), so
i'd figure you wouldn't need to do the extra stuff. Being perplexed, i
had to try an example. Given a file, /tmp/hmm, containing a single,
newline-terminated line:

tmpstr="echo 'this is a test\nhello world\n'"

I wrote a simple script that appends a new copy of this first line to the
end of the file (the code is indented with a tab, to distinguish it):

#!/usr/local/bin/python

hmm = open('/tmp/hmm', 'r')

line = hmm.readline()

hmm.close()

hmm = open('/tmp/hmm', 'a')
hmm.write(line)
hmm.close()

This is the simplest, most direct approach i could think of. And it
seems to work - after the first run, /tmp/hmm looks like:

tmpstr="echo 'this is a test\nhello world\n'"
tmpstr="echo 'this is a test\nhello world\n'"

Isn't that what you want, or am i missing something here??

ken
ken.manheimer@nist.gov, 301 975-3539