looping over the files in a directory

Scott David Daniels Scott.Daniels at Acm.Org
Fri May 14 12:40:18 EDT 2004


Mark J. Nenadov wrote:

> On Fri, 14 May 2004 15:32:32 +0000, Elaine Jackson wrote:
> 
>>Can anyone please tell me the actual syntax for saying something like this:
>>    for <file> in <directory>:
>>        <do something with the file>
> A simple example:
>     import os
>     path = '/home/bob/'
>     for f in os.listdir(path):
> 	  print f

A further clue for Elaine is:
listdir returns file "names".  Files are things the OS has; names are
how we talk about the files to the OS.  If you want to do anything with
the file, you'll have to decide what you want to do, and communicate the
_full_name_ of the file to the OS when you try to do it.

You can do that either by joining the path and file names, or by
changing the "working directory" so that the simple file name works.
Which you do depends on your overall goal.

This is purposely left a bit elliptical to leave you some work in
case this is a homework assignment.

-- 
-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list