problem with iteration

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Nov 4 11:39:28 EST 2007


Panagiotis Atmatzidis a écrit :
> Hello,
> 
> I managed to write some code in order to do what I wanted: Inject code
> in the right place, in some html files. I developed the program using
> small functions, one at the time in order to see how they work. When I
> tried to put these pieces of code together I got this error:
> TypeError: iteration over non-sequence
> 
> Here is the code snippet that has the issue
> 
> --------------
> def injectCode(path, statcode):
> 	for root, dir, files in os.walk(path, topdown=True):
> 		for name in files:
> 			html_files = re.search("html", name, flags=0)
> 			if html_files == None:

                         if html_files is None:

> 				print "No html files found in your path."
> 			else:
> 				for oldfile in html_files: <-- HERE IS THE ERROR
>                                   [rest of code here]

> 
> I'm learning through practice and this is my first program. The error
> may seem easy for you.

Indeed !-)

> However except from the explanation I'd like to
> know how can I handle situations like the one above. I tought that
> itering was valid there :-(

Obviously not. You may want to learn more about the re module, and what 
re.search returns. Anyway, if what you want is to find out if some file 
name contains the string 'html', you don't need regexps:

if 'html' in 'index.html':
   print "hurray"

Now I'm not sure you quite get how os.walk works - here, 'files' is a 
list of file *names*, so I don't see how you could expect one of it's 
elements to itself become a list of file names !-)

IOW, assuming you want to detect file names ending with '.html' in a 
given part of your directory tree, the following code might do:

def injectCode(path, statcode):
   html_files = []
   for root, dir, files in os.walk(path, topdown=True):
     for name in files:
       if name.endswith('.html'):
         html_files.append(os.path.join(root, name))
   if not html_files:
     print "No html files found in your path."
   else:
     for html_file in html_files:
       [rest of code here]

HTH



More information about the Python-list mailing list