[Tutor] access all files in one directory?

Gonçalo Rodrigues op73418 at mail.telepac.pt
Wed Nov 12 09:50:53 EST 2003


On Wed, 12 Nov 2003 14:52:29 +0100 (MET), you wrote:

>Hi,
>
>I would like to access all files in one directory, read their contents. I
>need them for a program. 
>
>So far I have a very simple program which takes two input files and creates
>one output file.  
>I need to give the program file1 and then one file after another in order to
>compare it with file1. In conclusion I need to create an output file for
>each of the files, except file1.  All the files I need (except file1) are in one
>directory.
>Can I give my program that directory to loop over all the files in it?  
>

What you need is the listdir function is the os module. Firing up the
interpreter:

>>> import os
>>> print os.listdir.__doc__
listdir(path) -> list_of_strings

Return a list containing the names of the entries in the directory.

	path: path of directory to list

The list is in arbitrary order.  It does not include the special
entries '.' and '..' even if they are present in the directory.
>>> for elem in os.listdir("C:\\"):
... 	print elem
... 
AUTOEXEC.BAT
[rest of list snipped]

With my best regards,
G. Rodrigues



More information about the Tutor mailing list