python noob, multiple file i/o

7stud bbxx789_05ss at
Fri Mar 16 16:38:54 CET 2007

The general idiom for altering lines in a file is to open the original
file and write the alterations to a temp file. After you are done
writing to the temp file, delete the original file, and change the
temp file name to the original file name.

If instead you were to read the whole file into a variable, and then
start overwriting the original file with the altered data, if your
program should happen to crash after writing one line to the file, all
the data in your variable would disappear into the ether, and your
file would only contain one line of data.  You can imagine what that
would be like if you had lots of important data in the file.

Here's my attempt that incorporates a temp file:

import os

filepath = "./change_files"

li = os.listdir(filepath)
for name in li:
        fullpath = filepath + "/" + name
        if os.path.isfile(fullpath):
                infile = open(fullpath, 'r')

                lastDotPos = fullpath.rfind(".")
                fileName = fullpath[:lastDotPos]
                ext = fullpath[lastDotPos:]
                tempName = fileName + ext + ".temp"

                outfile = open(tempName, "w")
                for line in infile:
                        outfile.write(line + "altered\n")

                os.rename(tempName, tempName[:-5])

I think it also needs some kind of check to make sure you have
permissions to delete the original file.

More information about the Python-list mailing list