Ruth
Ruth

Reputation: 5816

Checking a file exists (and ignoring case) in Python

I have a Python script and I want to check if a file exists, but I want to ignore case

eg.

path = '/Path/To/File.log'
if os.path.isfile(path):
   return true

The directory may look like this "/path/TO/fILe.log". But the above should still return true.

Upvotes: 3

Views: 3066

Answers (1)

wim
wim

Reputation: 362826

  1. Generate one-time a set S of all absolute paths in the filesystem using os.walk, lowering them all as you collect them using str.lower.
  2. Iterate through your large list of paths to check for existing, checking with if my_path.lower() in S.
  3. (Optional) Go and interrogate whoever provided you the list with inconsistent cases. It sounds like an XY problem, there may be some strange reason for this and an easier way out.

Upvotes: 1

Related Questions