On Thu, Jan 23, 2014 at 12:27 PM, MRAB <pyt...@mrabarnett.plus.com> wrote:
> On 2014-01-23 00:58, Larry Martell wrote:
>>
>> I have the need to check for a files existence against a string, but I
>> need to do case-insensitively. I cannot efficiently get the name of
>> every file in the dir and compare each with my string using lower(),
>> as I have 100's of strings to check for, each in a different dir, and
>> each dir can have 100's of files in it. Does anyone know of an
>> efficient way to do this? There's no switch for os.path that makes
>> exists() check case-insensitively is there?
>>
> You don't say which OS. Filenames in Windows, for example, are already
> case-insensitive.

There are weird use-cases for case insensitive filename matching on a
case sensitive file system. (For instance, a program that parses a
playlist file created on Windows. I did that a while ago - had to map
"Foobar.MID" to "FooBar.mid", matching case insensitively and
retrieving the actual case used on the FS.)

A good data structure is probably all you need. As Roy suggests,
iterate once over the directories - for instance, create a dict
mapping the .lower() of the filename to the original. Of course, then
you have to worry about collisions... though you may be able to
guarantee that they can't happen (in the above case, I was looking
through a directory tree that was unzipped straight from the Windows
collection, ergo no two filenames could differ only in case). Or maybe
you *think* you can guarantee it, but due to a bug you can't. (Ever
had a USB stick, formatted NTFS, with two files differing only in
case? Windows XP behaves... oddly. And rather amusingly.)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to