Fixing DOS Filenames
The heart of the prior script was findFiles
, a
function than 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 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
file names 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 like “import
spam” will sometimes fail for uppercase filenames.
To repair the damage everywhere in the thousand-file examples tree, I
wrote and ran Example 5-6. It works like this: For
every filename in the tree, it checks to see if 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 5-6. PP2E\PyTools\fixnames_all.py
######################################################### # Use: "python ..\..\PyTools\fixnames_all.py". # find all files with all upper-case names ...
Get Programming Python, Second 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.