[Tutor] newbie question--saving changes to a file

antonmuhin at rambler.ru antonmuhin at rambler.ru" <antonmuhin@rambler.ru
Tue Mar 4 12:41:29 2003


Hello Ron,

Tuesday, March 4, 2003, 6:54:23 PM, you wrote:

RN> How do I save the changes I make to a file say for example if I
RN> change old to new in a file and then want to save the new changes
RN> to another file?

RN> import string

RN> file = open('c:/file.txt')

RN> s = file.read()

RN> s.replace('old', 'new')

For your example:

inText = file(r"c:\file.txt").read()
inText.replace("old", "new")

outFile = file(r"output.txt", 'w')
outFile.write(inText)
outFile.close()

Several notes:
1. You'd better avoid names like 'file' for variables---it's actually
a built-in function.

2. You mustn't import string module (at least for your example)

3. Don't forget to close files (althoug I think Python might close it
for you, but still).

4. You may use r" to avoid \\ ugliness

5. If you're working with huse files, the following code would be
better:

outputFile = file(r"c:\output.txt", 'w')
for line in file(r"c:\file.txt"):
    # Pick a line
    line.replace("old", "new") # Process it
    outputFile.write(line)
outputFile.close()

-- 
Best regards,
 anton                            mailto:antonmuhin@rambler.ru