Directory-Tree Listing in Python

List directory tree structure in python?

Here's a function to do that with formatting:

import os

def list_files(startpath):
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
indent = ' ' * 4 * (level)
print('{}{}/'.format(indent, os.path.basename(root)))
subindent = ' ' * 4 * (level + 1)
for f in files:
print('{}{}'.format(subindent, f))

List directory tree structure in python from a list of path file

Possible solution:

paths = {
'main_folder': {
'file01.txt': 'txt',
'file02.txt': 'txt',
'folder_sub1': {
'file03.txt': 'txt',
'file04.txt': 'txt',
'file05.txt': 'txt',
'folder_sub1-1': {
'file06.txt': 'txt',
'file07.txt': 'txt',
'file08.txt': 'txt'
}
},
'folder_sub2': {
'file09.txt': 'txt',
'file10.txt': 'txt',
'file11.txt': 'txt'
}
}
}

# prefix components:
space = ' '
branch = '│ '
# pointers:
tee = '├── '
last = '└── '

def tree(paths: dict, prefix: str = ''):
"""A recursive generator, given a directory Path object
will yield a visual tree structure line by line
with each line prefixed by the same characters
"""
# contents each get pointers that are ├── with a final └── :
pointers = [tee] * (len(paths) - 1) + [last]
for pointer, path in zip(pointers, paths):
yield prefix + pointer + path
if isinstance(paths[path], dict): # extend the prefix and recurse:
extension = branch if pointer == tee else space
# i.e. space because last, └── , above so no more |
yield from tree(paths[path], prefix=prefix+extension)

for line in tree(paths):
print(line)

Ref: List directory tree structure in python?

Directory-tree listing in Python

This is a way to traverse every file and directory in a directory tree:

import os

for dirname, dirnames, filenames in os.walk('.'):
# print path to all subdirectories first.
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))

# print path to all filenames.
for filename in filenames:
print(os.path.join(dirname, filename))

# Advanced usage:
# editing the 'dirnames' list will stop os.walk() from recursing into there.
if '.git' in dirnames:
# don't go into any .git directories.
dirnames.remove('.git')

Python: Represent directory structure tree as list of lists

You can construct a dictionary from the flattened values, and then use recursion:

import re
d = ['.', ['A', 'B', 'C', 'D', 'E', 'F']], ['A', ['G', 'H']], ['A\\G', []], ['A\\H', ['K', 'L']], ['A\\G\\K', []], ['A\\G\\L', []], ['B', ['I', 'J']], ['B\\I', []], ['B\\J', []], ['C', []], ['D', []], ['E', []], ['F', ['M']], ['F\\M', []]
new_d = {re.findall('.$', a)[0]:b for a, b in d}
def _tree(_start):
if not new_d[_start]:
return _start
_c = [_tree(i) for i in new_d[_start]]
return [_start, *(_c if any(not isinstance(i, str) for i in _c) else [_c])]

print(_tree('.'))

Output:

['.', ['A', 'G', ['H', ['K', 'L']]], ['B', ['I', 'J']], 'C', 'D', 'E', ['F', ['M']]]

Edit: Python2 version:

import re
d = ['.', ['A', 'B', 'C', 'D', 'E', 'F']], ['A', ['G', 'H']], ['A\\G', []], ['A\\H', ['K', 'L']], ['A\\G\\K', []], ['A\\G\\L', []], ['B', ['I', 'J']], ['B\\I', []], ['B\\J', []], ['C', []], ['D', []], ['E', []], ['F', ['M']], ['F\\M', []]
new_d = {re.findall('.$', a)[0]:b for a, b in d}
def _tree(_start):
if not new_d[_start]:
return _start
_c = [_tree(i) for i in new_d[_start]]
return [_start]+(_c if any(not isinstance(i, str) for i in _c) else [_c])

print(_tree('.'))

Print out the whole directory tree

import os 
def Test1(rootDir):
list_dirs = os.walk(rootDir)
for root, dirs, files in list_dirs:
for d in dirs:
print os.path.join(root, d)
for f in files:
print os.path.join(root, f)

OR:

import os 
def Test2(rootDir):
for lists in os.listdir(rootDir):
path = os.path.join(rootDir, lists)
print path
if os.path.isdir(path):
Test2(path)

For the test file tree:

E:\TEST 
│--A
│ │--A-A
│ │ │--A-A-A.txt
│ │--A-B.txt
│ │--A-C
│ │ │--A-B-A.txt
│ │--A-D.txt
│--B.txt
│--C
│ │--C-A.txt
│ │--C-B.txt
│--D.txt
│--E

Running the following code:

Test1('E:\TEST') 
print '======================================='
Test2('E:\TEST')

You can see there are difference between the results:

>>>  
E:\TEST\A
E:\TEST\C
E:\TEST\E
E:\TEST\B.txt
E:\TEST\D.txt
E:\TEST\A\A-A
E:\TEST\A\A-C
E:\TEST\A\A-B.txt
E:\TEST\A\A-D.txt
E:\TEST\A\A-A\A-A-A.txt
E:\TEST\A\A-C\A-B-A.txt
E:\TEST\C\C-A.txt
E:\TEST\C\C-B.txt
=======================================
E:\TEST\A
E:\TEST\A\A-A
E:\TEST\A\A-A\A-A-A.txt
E:\TEST\A\A-B.txt
E:\TEST\A\A-C
E:\TEST\A\A-C\A-B-A.txt
E:\TEST\A\A-D.txt
E:\TEST\B.txt
E:\TEST\C
E:\TEST\C\C-A.txt
E:\TEST\C\C-B.txt
E:\TEST\D.txt
E:\TEST\E
>>>

To save them in a list:

import os 
files = []
def Test1(rootDir):
files.append(rootDir)
list_dirs = os.walk(rootDir)
for root, dirs, files in list_dirs:
for d in dirs:
files.append(os.path.join(root, d))
for f in files:
files.append(os.path.join(root, f))

import os
files = [rootDir]
def Test2(rootDir):
for lists in os.listdir(rootDir):
path = os.path.join(rootDir, lists)
files.append(path)
if os.path.isdir(path):
Test2(path)

Create a tree-style directory listing in Python

Try the following:

for path, dirs, files in os.walk("."):
print path
for file in files:
print os.path.join(path, file)

You do not need to print entries from dirs because each directory will be visited as you walk the path, so you will print it later with print path.



Related Topics



Leave a reply



Submit