[Tutor] storing and saving file tree structure
mhysnm1964 at gmail.com
mhysnm1964 at gmail.com
Mon Jan 25 23:21:33 EST 2021
Allan and Cameron,
I did send this to Cameron previously and forgot to add the group on to the
mail.
Thanks for the interest in the screen reader. It depends on the editor if
the right indent information is provided. Notepad++ seems to be okay. But it
is my default way of work.
I did find a solution which I will share below (excuse if the formatting
does not work):
import os, functools, ftplib
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):
if len(dirs) > 0:
folders = path[start:].split(os.sep)
subdir = dict.fromkeys(dirs)
parent = functools.reduce(dict.get, folders[:-1], dir)
parent[folders[-1]] = subdir
return dir
#load local books into title dict.
titles = get_directory_structure(r'e:\authors')
This did exactly what I wanted. Thanks for the information on sets. I will
save this as a excellent tip.
Sean
-----Original Message-----
From: Tutor <tutor-bounces+mhysnm1964=gmail.com at python.org> On Behalf Of
Alan Gauld via Tutor
Sent: Tuesday, 26 January 2021 11:55 AM
To: tutor at python.org
Subject: Re: [Tutor] storing and saving file tree structure
On 25/01/2021 09:20, mhysnm1964 at gmail.com wrote:
> As indents are a visual formatting structure. It is difficult for a
> screen reader user like myself to keep the blocks of code correctly
> indented. Thus why I am using the comments at the end of the code.
Ah, that makes sense. You just need to bear in mind the traps that they
introduce of prematurely ending blocks and inadvertently chopping blocks
into pieces.
> I will check out sets as that sounds useful.
OK, Also don;t forget the setdefault() method of dicts which is what saves
you from having to check for membership...
books.setdefault(anAuthor, set()).add(book)
Will always work because setdefault() returns the existing set for an
existing key and adds (and returns) a new empty set for a non-existent key.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
_______________________________________________
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list