I wrote some code that creates a dictionary that stores all the absolute paths of the folders in the current path as keys , and all their filenames as values , respectively. This code would only apply to paths that have folders that only contain stock images.
The code is the following:
import os
import re
# Main method
the_dictionary_list = {}
for name in os.listdir("."):
if os.path.isdir(name):
path = os.path.abspath(name)
print(f'\u001b[45m{path}\033[0m')
match = re.match(r'/(?:[^\\])[^\\]*$', path)
print(match)
list_of_file_contents = os.listdir(path)
print(f'\033[46m{list_of_file_contents}')
the_dictionary_list[path] = list_of_file_contents
print('\n')
print('\u001b[43mthe_dictionary_list:\033[0m')
print(the_dictionary_list)
The thing is, I want this dictionary to store only the last folder names as keys instead of their absolute paths, so I was planning to use this re /(?:[^\\])[^\\]*$
, which would take care of getting the last name (of a file or folder from a path given) and then add those last names as braces in the dictionary inside the for loop.
I wanted to try the above code first to see if it was doing what I wanted, but it wasn't, the value of the variable match
became None
on every iteration, which didn't make sense to me, everything else works fine.
So I would like to know what am I doing wrong here.
You are working more. First of all, the code is not recursive, so it will only scan the first level of subdirectories.
With the following code the variable
subdir
contains the name of a subdirectory. To form the complete path I must joinbase_dir
withsubdir
. In other words, there you have what you were looking for:After you check that it
path
is a directory:You can go in and list it:
and store the result under the desired key:
show
The complete code:
Based on @candid-moe's answer, I decided to rethink the above code in case I wanted to apply it only to the current directory (where the program would be).
This would be useful in case the user wants to run the program with a double click in a specific location ( my personal case ).
You can also just use
os.path.basename(dir...)
in such a way that the output is (according to the folders that I have added manually):