Monday, August 8, 2011

PYTHON iterate all files in a directory


To iterate through all the files within the specified directory (folder), with ability to use wildcards (*, ?, and [ ]-style ranges), use the following code snippet:
PYTHON:
  1. import os
  2. import glob
  3.  
  4. path = 'sequences/'
  5. for infile in glob.glob( os.path.join(path, '*.fasta') ):
  6.     print "current file is: " + infile
If you do not need wildcards, then there is a simpler way to list all items in a directory:
PYTHON:
  1. import os
  2.  
  3. path = 'sequences/'
  4. listing = os.listdir(path)
  5. for infile in listing:
  6.     print "current file is: " + infile

No comments:

Post a Comment