Fixing DOS Filenames

The heart of the prior script was findFiles, a function that knows how to portably collect matching file and directory names in an entire tree, given a list of filename patterns. It doesn’t do much more than the built-in find.find call, but it can be augmented for our own purposes. Because this logic was bundled up in a function, though, it automatically becomes a reusable tool.

For example, the next script imports and applies findFiles, to collect all filenames in a directory tree, by using the filename pattern * (it matches everything). I use this script to fix a legacy problem in the book’s examples tree. The names of some files created under MS-DOS were made all uppercase; for example, spam.py became SPAM.PY somewhere along the way. Because case is significant both in Python and on some platforms, an import statement such as import spam will sometimes fail for uppercase filenames.

To repair the damage everywhere in the thousand-file examples tree, I wrote and ran Example 7-6. It works like this: for every filename in the tree, it checks to see whether the name is all uppercase and asks the console user whether the file should be renamed with the os.rename call. To make this easy, it also comes up with a reasonable default for most new names—the old one in all-lowercase form.

Example 7-6. PP3E\PyTools\fixnames_all.py

########################################################################## # Use: "python ..\..\PyTools\fixnames_all.py". # find all files with ...

Get Programming Python, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.