Image of the glider from the Game of Life by John Conway
Skip to content

Recursion In Python

I took my Perl script that I wrote some time ago, and rewrote it in Python. The exercise of the initial Perl script, was to get a better handle on the language using recursion, and to inventory my Ogg Vorbis collection of music. The same reasons were used for this Python version. This script traverses a directory tree, full of Ogg Vorbis files, printing out to a file in indented form, the contents, and counting the number of Ogg Vorbis files it comes across. You'll notice the lack of comments, as I find Python code much more readable than Perl code. It should be fairly obvious what this script is doing.

#!/usr/bin/env python
import dircache, os
counter = 0

def PrintFiles(indent):
    global counter
    thisDir = os.getcwd()

    for file in dircache.listdir(thisDir):
        if (file.endswith('ogg') or os.path.isdir(file)) and not file.startswith('.'):
            if file.endswith('ogg'):
                counter += 1
            oggFile.write('%s%s\n' %(indent, file))

            if os.path.isdir(file):
                PrintFiles(indent + '  ')

    oggFile = open('oggfiles.txt', 'w')
except IOError, e:
    print "Unable to open 'oggfiles.txt' for writing: ", e
    oggFile.write('\nCurrent number of ogg files: %d\n\n' %(counter))

{ 14 } Comments

  1. new back | August 9, 2007 at 6:53 am | Permalink

    Doesn't Python support omiting the empty parenthesis, like "oggFile.close"? I like that feature in Ruby, but then again Python has that thing with with space...

  2. Aaron | August 9, 2007 at 7:04 am | Permalink

    @new back- Yes, it does support omitting empty parenthesis in this case.

  3. Igor | August 9, 2007 at 7:23 am | Permalink

    @new back: END END END... thats why ruby sucks ;)... damn remains me Visual Basic :S

    @Aaron: You know what will be cool that you use pure functional programming like in languages like Haskell... without for and variables.

    btw, recursion in python have a very short limit, so, its better to use C or another stuff to do recursion, anyway for your purpose this script works very good.

  4. Mircea | August 9, 2007 at 7:48 am | Permalink

    is the lack of error checking after open() or write() reminiscent of C coding? 🙂
    it's programs like this posted on the web that make computer science such a screwed up world. no offense.i noticed the lack of comments but that's no excuse for the lack of error checking. this is why we have exceptions. See for an example. Please remove (or fix) this script from the web, so poor coding perpetuates less. I understand that it was meant as a quick hack for personal use but in that case it should be treated as such and not posted on the web, or, if posted, it should have a big red flag saying "this is an example of bad coding, do not use it!". I hope you take this as constructive criticism not otherwise.

  5. Vincent | August 9, 2007 at 7:49 am | Permalink

    Not sure if the exercise was to translate a Perl script to Python, or simply to list the directory content recursively.
    On the second case, module "os" offers the recursive method "walk()" (doc here).

    @new back:
    Not to start the flamewar, but I do not see calling methods without parenthesis a "feature", in Ruby or Perl, especially when reading someone else's code (damn self-proclaimed Perl guru coworkers)

  6. Aaron | August 9, 2007 at 8:20 am | Permalink

    @Igor- What do you mean "recursion in python have a very short limit"?

    @Mircea- Thank you for your criticism. It has been duly noted.

    @Vincent- Yes, the script was to teach myself Python. Of course, there is more than one way to solve an algorithm. This was my approach, obviously, not knowing about walk(). 🙂

  7. new back | August 9, 2007 at 8:32 am | Permalink

    Vincent, in Ruby you don't "call methods". Instead both calling methods and using variables are sending messages to objects. In fact there is no difference between a method and variable. The normal way of calling class methods is just syntactic sugar. The way it works takes some time getting used to but it is definitely most of the time a feature. I would omit empty parenthesis simply not to have to type them 🙂

    I don't want to start a language war myself either. I hate the begin..end on Ruby, it's the largest single flaw it has and plain stupid. I would like them to adopt the Python way actually.

  8. Paddy3118 | August 9, 2007 at 12:06 pm | Permalink

    Comments on the comments:
    1&2: oggfile.close is the function, oggfile.close() calls the function and closes the file.

    4: open() and write() will raise exceptions when necessary leading to a meaningful traceback if not explicitly caught. It could be that not catching the exceptions is the intended behaviour.

    - Paddy.

  9. George | August 9, 2007 at 10:47 pm | Permalink

    @Mircea: as a person learning how to code (at least learning how to do it well) i find examples like these useful even if they aren't fully error-checked. if someone is clueless enough to write important code without proper error-checking in the first place, not putting stuff like this out there on the internet is not going to deter them from doing so. That's like saying that "not publishing security exploits leads to more secure software". Just because something isn't published doesn't mean it doesn't exist.

  10. Anonymous | August 11, 2007 at 2:58 pm | Permalink


    You're completely and totally welcome to use curly braces when using ruby. Curly braces are totally understood, and valid.

  11. Jason | August 11, 2007 at 2:59 pm | Permalink

    Hmmm. Anonymous? Bah!
    Aaron: That WPOpenID plugin has a race condition in it.

  12. martin | August 15, 2007 at 12:29 am | Permalink

    using chdir(dirent) ... chdir("..") will break on symlinks...
    either do fancy fchdir things or pass a relative path down as parameter...

  13. Igor | August 18, 2007 at 1:29 pm | Permalink

    Hi all, Aaron ask me what I mean with the Python recursion limitation well, I made some research and the results are very interesting you can see a comparison between Python and C# here(in my blog):

    Waiting for your comments.

  14. Aaron | August 21, 2007 at 10:02 pm | Permalink

    @Igor- I still don't understand what you mean my recursion limits in Python. Recursion is implemented on as well as the author deems. If you are meeting limits with your Python recursion, then you need to rethink your algorithm, or learn the language. I don't know what else to say about that.

Post a Comment

Your email is never published nor shared.