2

User input two strings, one is filename and the other one is folder. The filename variable is a path to some file on disk. And the folder variable is a path to some folder on disk. I want to know if the file is located in the folder (either directly or in its sub folders).

For example:

isContains("C:\\a.txt", "C:\\") # True
isContains("C:\\a.txt", "C:\\a") # False
isContains("C:\\a.txt", "D:\\") # False
isContains("C:\\a\\b\\c\\d.txt", "C:\\") # True
isContains("C:\\a\\b\\c\\d.txt", "C:\\a\\b") # True

What I have done yet:

import os
isContains = lambda filename, folder: os.path.abspath(filename).startswith(os.path.join(os.path.abspath(folder), ''))

But I believe there must be some more elegant ways I didn't find out. As these code looks too complex. How should I implement this function?


My program is running on Windows. But I want the code be platform independent.

3
  • 2
    It's already implemented in pathlib: Path.is_relative_to(). You can just do Path(filename).is_relative_to(folder). Alternatively you can use os.path.commonprefix() and check for non-empty return: commonprefix((filename, folder)) Commented Jan 16, 2022 at 14:30
  • @OlvinRoght But os.path.commonprefix(('c:\\a\\b\\c\\d.txt', 'c:\\a\\d')) is not empty (should be false) Commented Jan 16, 2022 at 14:38
  • Exactly, I've not thought about all possible cases writing first comment. Option with commonprefix() requires additional return validation to meet all conditions, so if you don't want additional (unnecessary) headache - use pathlib. Commented Jan 16, 2022 at 14:38

1 Answer 1

2

If you have no strict requirement to use os.path, I'd recommend for all path-related work use pathlib, it will save you lot of time.

There's special method of Path(PurePath) class which does exactly what you're trying to implement - Path.is_relative_to(). Basically, you just need to initialize Path from your filename and call this method with folder:

Path(filename).is_relative_to(folder)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.