Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File paths hierarchial sort in python

Input file contains list of file paths. suggest algorithm to do hierarchy sort output like below

Input

A/file1
A/B/C/D/file3
A/B/file1
A/B/file2
A/B/C/D/file1
A/file2
A/W/X/Y/Z/file1
A/W/file1
A/W/X/file1
A/file3
A/B/C/file1
A/W/X/Y/file1
A/B/file2

Expected output

A/file1
A/file2
A/file3

A/B/file1
A/B/file2

A/B/C/file1

A/B/C/D/file1
A/B/C/D/file3


A/W/file1

A/W/X/file1

A/W/X/Y/file1

A/W/X/Y/Z/file1

tried coding like below, result is not coming as expected

import sys,os
d1,d2 = '',''
l1 = [ x for x in open(sys.argv[1])]
s2 = sorted(l1,key = lambda x : len(x.split('/')))
for linE in s2:
    f1 = linE.strip('\n')
    d1 = os.path.dirname(f1)
    if d1 != d2 : print
    d2 = d1
    print linE,

Current output

A/file1
A/file2
A/file3

A/B/file1
A/B/file2

A/W/file1

A/B/file2

A/W/X/file1

A/B/C/file1

A/B/C/D/file3
A/B/C/D/file1

A/W/X/Y/file1

A/W/X/Y/Z/file1

please help me with an algorithm to do the same

like image 528
user1228191 Avatar asked Apr 19 '15 16:04

user1228191


People also ask

How do you manage paths in Python?

To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest: Notice two things here: You should use forward slashes with pathlib functions. The Path() object will convert forward slashes into the correct kind of slash for the current operating system.

What is file path in Python?

The file path is a string that represents the location of a file. It's broken up into three major parts: Folder Path: the file folder location on the file system where subsequent folders are separated by a forward slash / (Unix) or backslash \ (Windows)

How do you arrange variables in Python?

Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.


1 Answers

str = """A/file1
A/B/C/D/file3
A/B/file1
A/B/file2
A/B/C/D/file1
A/file2
A/W/X/Y/Z/file1
A/W/file1
A/W/X/file1
A/file3
A/B/C/file1
A/W/X/Y/file1
A/B/file2"""

import string
files = string.split(str, "\n")

import os.path
std = sorted(files, key=lambda file: (os.path.dirname(file), os.path.basename(file)))

print std[0]
for i in range(1,len(std)):
    if os.path.dirname(std[i]) != os.path.dirname(std[i-1]):
        print ""
    print std[i]
like image 109
Amit Kumar Gupta Avatar answered Sep 20 '22 10:09

Amit Kumar Gupta