How to write to tempfile, remove whitespace, and copy to source ..?

Greg Jorgensen gregj at pobox.com
Sun Jan 21 13:31:33 EST 2001


tempfile.TemporaryFile() creates a new temporary file and opens it for
you; the value you get back is a file object ready for writing, so you
don't need to open it. But since you need the temporary file name so
you can rename it, you need to use the mktemp() method instead:

----
import glob, fileinput, os, tempfile, string

files = glob.glob(r'e:\text\*.txt')
for filename in files:
    tempname = tempfile.mktemp()
    temp = open(tempname, 'w')
    for s in fileinput.input(filename):
        temp.write(string.strip(string.join(string.split(s))))
    temp.close()
    os.remove(filename)
    os.rename(tempname, filename)
---

I would add exception handling before deploying; there are several
places where file operations can fail.

--
Greg Jorgensen
Portland, Oregon, USA
gregj at pobox.com



In article <t6m772ggf7gj8a at corp.supernews.com>,
  "Randolph MacKenzie" <rmack at eznet.net> wrote:
> I want a module that will remove the extra whitespace from all text
files in
> a target directory. I want to use the tempfile command (on a
Windoze2000
> box). I guess I'm having trouble opening the tempfile and appending
to it...
> and then, after processing it, I need to copy (overwrite) it to
source file.
>
> Any suggestions ?
>
> # X2space.py removes all extra whitespace from textfiles
>
> target = "E:\\text\\"
> import glob, fileinput, os, shutil, string, tempfile
> filelist = glob.glob(target+"*.TXT")
>
> for fl in filelist:
>  L3 =[];
>  tmp = tempfile.TemporaryFile('a')
>  #tmpfile = open(tmpflname,'a')
>  for line in fileinput.input(fl):
>   tmp.write(string.strip(string.join(string.split(line))))
>  tmp.close()
>  shutil.copyfile(tmp,fl)
>


Sent via Deja.com
http://www.deja.com/



More information about the Python-list mailing list