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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #!/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): os.chdir(file) PrintFiles(indent + ' ') os.chdir('../') try: oggFile = open('oggfiles.txt', 'w') except IOError, e: print "Unable to open 'oggfiles.txt' for writing: ", e else: PrintFiles('') oggFile.write('\nCurrent number of ogg files: %d\n\n' %(counter)) oggFile.close() |
{ 14 } Comments