David542
David542

Reputation: 110432

Way to ignore case in iteration of glob

Is there a simpler way to do the following to iterate over xls files regardless of capitalization?

for file in [glob.glob(os.path.join(dir, '*.xls')), glob.glob(os.path.join(dir, '*.XLS'))]:

Upvotes: 8

Views: 5486

Answers (3)

Keith Bennett
Keith Bennett

Reputation: 4970

A scripting language could help here. For example, in Ruby, to see all filespecs containing 'gem' case insensitively, this would work:

ruby -e 'puts Dir["*"].grep /gem/i'

This could be abstracted into a script that offered parameterized search strings and directories:

#!/usr/bin/env ruby
# lsi - ls case insensitive

mask = /#{ARGV[0]}/i
dir = ARGV[1] || '.'
puts Dir[File.join(dir, '*')].grep(mask)

Upvotes: 0

sth
sth

Reputation: 229784

You could do the matching "manually" without glob:

for file in os.listdir(dir):
    if not file.lower().endswith('.xls'):
        continue
    ...

Upvotes: 3

phihag
phihag

Reputation: 288200

glob and the underlying fnmatch have no flag for case-independence, but you can use brackets:

for file in glob.iglob(os.path.join(dir, '*.[xX][lL][sS]')):

Upvotes: 16

Related Questions