[Tutor] Files, directories and syntax
Karen Windus
kwindus@LanMinds.Com
Thu, 1 Mar 2001 11:54:28 -0800 (PST)
Hi -
I'm somewhat new to python. I am trying to change a line in every html
file in a directory if there is a match on the text string I'm searching
for. So I'm using glob to match a file pattern. Then I want to loop
through every file, loop through every line, so a search on the regexp
that I've set up and if there is a match, at this point, I just would be
happy with printing out some debugging code and then closing (and
eventaully saving) the file.
When I run the following code now, I get a syntax error on 'file =
open(i,"rw")'
I guess I'm not sure how to populate the file object (when I try and OPEN
a file in other words) with the actual name of the file. So I'm using i
in a loop. Is that wrong? In other languages that would work I
think. Anyway, I don't know if I'm on the right track or not.
Here's what I have so far:
#! /usr/bin/env python
def change_lines(directory = None):
import glob,re
result = []
filepattern = '*.{html}'
filelist = glob.glob1(directory,filepattern)
regexp = re.compile(r"Your Turn")
for i in filelist:
file=open(i,"rw")
print "We opened a file"
for file in filelist:
lines = filenames.readlines()
for line in lines:
result = regexp.search(line)
if result == None:
print "Result was equal to None"
elif 'Your' in line or 'Turn' in line:
print "we had a match"
print result
else: print "Nothing happened"
return result
file.close()
change_lines()
Thanks,
Karen