import os.path # glob is a simple and useful python module. # It uses simple regular expressions to match # directories and files for a given path. If # you've ever used the command line to 'ls' or # 'dir' the currently directory you may be aware # that the directory accepts * or ? or [] to # match patterns. glob is a python implementation # of this functionality. import glob import os # find all the .txt files in the current working directory print glob.glob('*.TXT') # output: # ['LICENSE.txt', 'NEWS.txt', 'README.txt'] # you can also specify a full path # Here I'm searching for dll files in python 2.6 print glob.glob('C:\Python26\DLLs\*.dll') # output: # ['C:\\Python26\\DLLs\\sqlite3.dll', # 'C:\\Python26\\DLLs\\tcl85.dll', # 'C:\\Python26\\DLLs\\tclpip85.dll', # 'C:\\Python26\\DLLs\\tk85.dll'] # If you are expecting a great deal of results # you should use the glob.iglob method that returns # matches as it goes and does not load everything # into memory first. # glob.iglob() example f = glob.iglob('C:\Python26\Lib\*') spitItOut = True while spitItOut: try: fileNameAndPath = f.next() # since glob gives you the full path you can # use the output with some of the os module's methods if os.path.isfile(fileNameAndPath): fileNameAndPath += " is a file." else: fileNameAndPath += " is not a file." print fileNameAndPath except StopIteration: spitItOut = False #output (snipped a bit...since there a lot): # C:\Python26\Lib\abc.py is a file. # ....[snip] # C:\Python26\Lib\compiler is not a file. # ...[another snip] # C:\Python26\Lib\getopt.py is a file. # C:\Python26\Lib\getopt.pyc is a file. # C:\Python26\Lib\getpass.py is a file. # C:\Python26\Lib\gettext.py is a file. # C:\Python26\Lib\glob.py is a file. # C:\Python26\Lib\glob.pyc is a file.
A python example based blog that shows how to accomplish python goals and how to correct python errors.
Showing posts with label isfile. Show all posts
Showing posts with label isfile. Show all posts
Thursday, October 1, 2009
Python - using glob to get lists of files and directories
Wednesday, September 16, 2009
Python - determine an image's type (regardless of extension)
# iterate through all the files in the current directory # identify the type of image file (regardless of extension) import os import imghdr # list files in the current working directory for f in os.listdir('.'): if os.path.isfile(f): imgtype = imghdr.what(f) if imgtype is None: imgtype = "not image" print "'" + f + "'" + " is type " + imgtype #output: (for me) #'2007 Oct 31 146.jpg' is type jpeg # #'2007 Oct 31 147.jpg' is type jpeg # #'2007 Oct 31 148.jpg' is type jpeg # #'2007 Oct 31 149.image' is type jpeg # #'2007 Oct 31 150.jpg' is type jpeg # #'big kitty.GI' is type gif # #'eric.image' is type jpeg # #'LICENSE.txt' is type not image # #'NEWS.txt' is type not image #
Subscribe to:
Posts (Atom)