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
Related posts
- How to remove ^M characters from a file with Python — posted 2011-10-03
- Options for listing the files in a directory with Python — posted 2010-04-19
- Monitoring a filesystem with Python and Pyinotify — posted 2010-04-09
- os.path.relpath() source code for Python 2.5 — posted 2010-03-31
- A hack to copy files between two remote hosts using Python — posted 2010-02-08