s c h e m a t i c s : c o o k b o o k

/ Cookbook.FileProcessingAllFilesInADirectory

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Processing All Files in a Directory

Problem

You want to do something to each file in a particular directory.

Solution

Use PltScheme's standard function directory-list to retrieve the contents in a directory and do something with them.

(for-each do-something-with-the-contents
          (map (lambda (f)
                 (string-append path "/" f))
               (directory-list path)))

You just have to take in account that directory-list returns a list of all files and directories in the directory specified by path. If path is omitted, a list of files and directories in the current directory is returned.

If you need to process the files only. We can define a new procedure that only retrieves the files in a directory like this:

(require (lib "list.ss" "srfi" "1"));; to use the filter procedure

;; directory-list-files: String -> (listof String)
;; Obtains a list with the files (only) in the specified path
(define (directory-list-files path)
  (filter (lambda (v)
            (file-exists? (string-append path "/" v)))
          (directory-list path)))

So our first code will turn into

(for-each do-something-with-the-contents
          (map (lambda (f)
                 (string-append path "/" f))
               (directory-list-files path)))

Finally, in the previous examples we used the for-each procedure, that applies a procedure to each element in a list, but returns void. If you want to return a value you may want to use the map procedure instead of for-each.

Discussion


Comments about this recipe

Contributors

-- IvanHernandez - 03 Jun 2004

CookbookForm
TopicType: Recipe
ParentTopic: FileRecipes
TopicOrder: 999

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, this material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest