[newbie] Read file, and append?

Gary Herron gherron at islandtraining.com
Tue Dec 25 04:14:37 EST 2007


Gilles Ganault wrote:
> Hello
>
> I'd just like to open each file in a directory with a given extension,
> read it to search for a pattern, and, if not found, append data to
> this file. The following doesn't work:
>
> ======
> import glob,re
>     
> f = open("activate.tmpl", "r") 
> template = f.read()
> template = "\r\n" + template
> f.close()
>
> for file in glob.glob('*.frm'):
> 	#BAD f = open(file, "r+") 
> 	#f = open(file, "r") 
> 	#f = open(file, "a") 
>
> 	f = open(file, "rw") 
> 	if not re.search('Form_Activate',f.read(), re.I):
> 		#print "Not in " + file
>
> 		#IOError: [Errno 0] Error
> 		f.write(template)
>
> 		f.close()
> ======
>
> What am I doing wrong?
>   
I've never used "rw" mode, and suspect that's the cause of your
problems here. I see no need for it here.  Since you are going
to read the whole file in at once, you might as well write it (plus
the modification) all out again.

Also I notice that your close is called only if the pattern is not
found, even though you should call it for *every* file opened.

Also, you are not using the regular expression machinery as intended.
You are really just searching for a know and constant substring.  Use
"in" instead.

Also I *always* read in binary mode (thereby forcing Windows to keep
it's damn hands off my bytes).

Also, don't use variables named 'file'.  That overrides an important
builtin.

Here's what I'd end up with.  (This is untested.)


import glob
   
f = open("activate.tmpl", "rb")
template = "\r\n" + f.read()
f.close()

for fname in glob.glob('*.frm'):
    inf = open(fname, "rb")
    content = inf.read()
    inf.close()

    if 'Form_Activate' not in content:
        print "Not in", fname

        outf = open(fname, 'wb')
        outf.write(content)
        outf.write(template)
        outf.close()



Gary Herron




More information about the Python-list mailing list