Split on dot but build up per level to full string

Hello / Good morning (CET TZ),

I'm quite new to Python, but seem to be finding my way quite well, as the language is good to understand and I really like the indentation requirement to keep it clean!

I'm trying to do some mailbox management with imap_tools ( https://pypi.org/project/imap-tools/ ) and before moving a message to a folder, I want to create the folder structure.

As I couldn't find if I could do a create folder action on the full string e.g. "INBOX.mainfolder.subfolder.subofsubfolder" I wanted to split it up per dot:

  • INBOX
  • mainfolder
  • subfolder
  • subofsubfolder

I have this part ( I stripped the mailbox parts, to keep it to my question ) :

#!/usr/bin/python3

from imap_tools import MailBox, AND, OR, NOT
from pprint import pprint

def createIfNotExistAndMoveToFolder(mailboxStream, searchTerm, msguid, MoveToFolder):
	folder_original = MoveToFolder
	folder_split = folder_original.split(".")
	pprint(folder_split)
	# I have to join it back together here, but keeping the 'levels'.

mailboxStream = "fake"
createIfNotExistAndMoveToFolder(mailboxStream, 'search word / term', '1', 'INBOX.mainfolder.subfolder.subofsubfolder')

And then join it to become, and this is what I can't figure out:

  • INBOX.mainfolder
  • INBOX.mainfolder.subfolder
  • INBOX.mainfolder.subfolder.subofsubfolder

So I'm sure I've create each level of the folder structure separately, I've searched Google and StackOverflow for this and the only way I could think of explaining it is 'Split on dot but build up per level to full string' which doesn't get me the result(s) I'm looking for to help.

Could anyone help me, either by suggesting a better/other search term, or possibly explaining how to achieve such build up?

Thanks in advance!

Posted Dec 23, 2021, 8:19 AM UTC · edited

13
Rhoderick•

Couldn't you just call

".".join(x)

where x is your folder_split, then just remove the last element of the list

x = x[:-1]

And just loop over that untill the list is empty? (Or I suppose untill it only has one element, if you don't want to generate "INBOX",)

3
shiftybyte•

Create a loop over the items in the split list, and add it up back together manually, each loop cycle you will have the "step" you need.

example_list = ["mainfolder", "subfolder", "subofsubfolder"]
result = "INBOX"
for item in example_list:
    result += "." + item
    print(result)
2
DanielB1990OP•

Exactly what I was lookin for, thanks!

​

Can't get the formatting sorted, therefor: https://pastebin.com/jCF43uPP

1