python noob, multiple file i/o

7stud bbxx789_05ss at yahoo.com
Fri Mar 16 12:36:20 EDT 2007


On Mar 16, 9:38 am, "7stud" <bbxx789_0... at yahoo.com> wrote:
> -----
> 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")
>                 outfile.close()
>
>                 os.remove(fullpath)
>                 os.rename(tempName, tempName[:-5])
> ---------------
>

I did some unnecessary name manipulation in there.  Try this:

filepath = "./change_files"

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

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

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




More information about the Python-list mailing list