Python test given path to file in given path of folder
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.
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)