Creating a list of files in a directory

Roman Suzi rnd at onego.ru
Wed Nov 7 19:24:54 CET 2001


On Wed, 7 Nov 2001, Jeff Klassen wrote:

>Hello,
>
>I am new to Python. As a non-programmer I am encouraged by the level of
>'success' I feel I have had, relative to similar learning attempts in other
>languages.
>
>I would like to simply do the following:
>- read all of files of a particular form (e.g. *.cev) from a particular
>directory
>- manipulate them with a series of re.sub expressions
>- write each file to its own output file with a certain form (e.g. *.out).
>
>I have been able to create the re stuff, and process individual files.
>However, I cannot get a for loop to do everything in a directory.
>
>Here is the code I came up with. (I am wanting to create a list of all files
>that conform to *.cev)
>
>----------------------------
>import dircache
>import re
>
>workingdir=dircache.listdir('/jobs/python/learning/')
>filespec = re.compile(r'.*?\.cev')
>filestoprocess = []
>
>for allfiles in workingdir:
>    matchedfile=filespec.match(allfiles)
>    filestoprocess.append(matchedfile.group())
>
>print filestoprocess
>----------------------------
>
>When I run this script I am returned:
>AttributeError: 'None' object has no attribute 'group'

There is glob module which allow to do it simpler:

-------------------------------------------------------
from glob import glob
filestoprocess = glob('/jobs/python/learning/*.cev')
-------------------------------------------------------

Maybe, you will also need

os.chdir(), os.path.basename() and os.path.dirname()
functions to change into specific dir and analize
file names.

Also, do not forget map() capability to eval function for
each list member. It could be useful while solving
your problem.

Sincerely yours, Roman Suzi
-- 
_/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/
_/ Wednesday, November 07, 2001 _/ Powered by Linux RedHat 6.2 _/
_/ "I used to be indecisive. Now I'm not so sure." _/





More information about the Python-list mailing list