Python maps a file system to a directory structure: it works, but how?

I understand the directory. I found a fragment here that works well, but I can’t understand why and how their variable is dirupdated where it is installed.

What I'm trying to do is leave empty folders

import os

def get_directory_structure(rootdir):
    """
    Creates a nested dictionary that represents the folder structure of rootdir
    """
    dir = {}
    rootdir = rootdir.rstrip(os.sep)
    start = rootdir.rfind(os.sep) + 1
    for path, dirs, files in os.walk(rootdir):
        folders = path[start:].split(os.sep)
        subdir = dict.fromkeys(files)
        parent = reduce(dict.get, folders[:-1], dir)
        parent[folders[-1]] = subdir
    return dir

dir set to the same value as the parent line:

        parent[folders[-1]] = subdir

How did it happen?

dirchanged and accepted as input in the line reduce, but it is not installed there, but in the next line.

Any idea?

I want to be able to leave empty folders and better find an elegant way to do this; Do I have to give up and pass through the dict as a second pass?

[Edit after resolved], , dir, , dir.

, vars :

dirtoken_dict
folderspath_as_list
subdirfiles_in_dir
parentfull_dir ( full_dir)

, , , .

+4
2

dir reduce. , , .

reduce . :

accum_value = function(accum_value, x)

accum_value , initializer, dir, , dict.get.

+2

, :

, .

Reduce will apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.

:

reduce(function, sequence[, initial]) -> value

, , , .

:

>>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
15
>>>
smiliar to ((((1+2)+3)+4)+5)

:

>>> reduce(lambda x, y: x+y, [], 1) 
1
>>>

, :

, dict.get():

>>> d = {'a': {'b': {'c': 'files'}}}
>>> dict.get(d,'a')
{'b': {'c': 'files'}}
>>>

, dict.get reduce, :

>>> d = {'a': {'b': {'c': 'files'}}}
{'b': {'c': 'files'}}
>>> reduce(dict.get, ['a','b','c'], d)
'files'
>>>

:

>>> dict.get(dict.get(dict.get(d,'a'),'b'),'c')
'files'
>>>

, dict, :

>>> reduce(dict.get, [], {})
{}
>>>

:

dir snippet!= dir(), , .

parent = reduce(dict.get, folders[:-1], dir)

, [: - 1] - . dir is empty_dictionary.

, , .

+3

Source: https://habr.com/ru/post/1524483/


All Articles