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.
pathlib:Path.is_relative_to(). You can just doPath(filename).is_relative_to(folder). Alternatively you can useos.path.commonprefix()and check for non-empty return:commonprefix((filename, folder))os.path.commonprefix(('c:\\a\\b\\c\\d.txt', 'c:\\a\\d'))is not empty (should be false)commonprefix()requires additional return validation to meet all conditions, so if you don't want additional (unnecessary) headache - usepathlib.