Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading