Creating a list of files in a directory
Fredrik Lundh
fredrik at pythonware.com
Wed Nov 7 13:56:46 EST 2001
Jeff Klassen wrote:
> 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
files = glob.glob("*.cev")
for file in files:
> - manipulate them with a series of re.sub expressions
are you sure?
> - write each file to its own output file with a certain form (e.g. *.out).
note that there's plenty of filename-manipulating stuff
in the os.path module.
for example:
# split filename in file and extension part
file, ext = os.path.splitext(file)
outfile = file + ".out"
> workingdir=dircache.listdir('/jobs/python/learning/')
you're sure using somewhat confusing names; are you sure
you didn't really mean:
workingdir='/jobs/python/learning/'
allfiles = dircache.listdir(workingdir)
> filespec = re.compile(r'.*?\.cev')
> filestoprocess = []
>
> for allfiles in workingdir:
> matchedfile=filespec.match(allfiles)
for file in allfiles:
matchedfile = filespec.match(file)
> filestoprocess.append(matchedfile.group())
>
> print filestoprocess
> ----------------------------
>
> When I run this script I am returned:
> AttributeError: 'None' object has no attribute 'group'
the match method returns a match object (with a group method)
if it matches. but if it doesn't, you get None.
this should work (but you probably want glob.glob anyway):
matchedfile=filespec.match(allfiles)
if matchedfile:
filestoprocess.append(matchedfile.group())
hope this helps!
</F>
More information about the Python-list
mailing list