SaltyCrane Blog — Notes on JavaScript and web development

How to get the filename and it's parent directory in Python

import os.path

def get_file_with_parents(filepath, levels=1):
    common = filepath
    for i in range(levels + 1):
        common = os.path.dirname(common)
    return os.path.relpath(filepath, common)

print get_file_with_parents(
    '/opt/xyzabc/etc/yaml/working/group1/vendor1.yaml', 1)
print get_file_with_parents(
    '/opt/xyzabc/etc/yaml/working/group1/vendor1.yaml', 2)

Results:

group1/vendor1.yaml
working/group1/vendor1.yaml

Comments