fnmatch() function
Chris Lawrence
chris at lordsutch.com
Sat May 17 00:37:01 EDT 2003
In article <3ec580e6$0$15841$afc38c87 at news.optusnet.com.au>, Psybar
Phreak wrote:
> hi everyone
>
> here's my situation - i have a sub-folder (called diaries) i have some files
> and sub-folders within that folder. the files ahve different extensions
> (*.dia, *.eve).
>
> what i want to do it go through all the files in the folder that end in
> *.dia, and print the first 2 lines from them.
>
> now ive just found the function called fnmatch() (after trying to use glob
> only to realise its for PATHname and not FILEnames)
Uh, why not just use glob? You don't need to specify a full pathname
in glob.glob(). Try e.g.:
import glob, os, sys
os.chdir("c:/my_directory/diaries") # Change this, or omit it if using . is OK
for fn in glob.glob('*.dia'):
fob = open(fn, 'r')
sys.stdout.writelines([fob.readline(), fob.readline()])
fob.close()
You can drop the fob.close() call if you're not worried about a future
version of Python running out of file descriptors.
If you're in a seriously masochistic mood, you can duplicate the
functionality of glob.glob() with fnmatch and os.listdir [which is
essentially what glob does internally anyway], but why bother?
Chris
--
Chris Lawrence <chris at lordsutch.com> - http://blog.lordsutch.com/
More information about the Python-list
mailing list