In my example directory structure, there are 3 folders under Project - das, des, and dga. There's also a file randomfile.xlsx Within each folder are files and subfolders.
Project
┣ das
┣ des
┃ ┣ subfolder_des1
┃ ┃ ┗ COM-EL-DES-0002-0.pdf
┃ ┗ COM-EL-DES-0001-0.pdf
┣ dga
┃ ┣ subfolder_dga1
┃ ┃ ┗ 3500-ST-DGA-0047-0.pdf
┃ ┣ subfolder_dga2
┃ ┃ ┣ 3500-ST-DGA-0046-0.pdf
┗ randomfile.xlsx
My code uses os.walk to return a directory tree list of values under the Project folder, which I add to a pandas DataFrame. e.g.
c:/Project/das
c:/Project/des
c:/Project/dga
c:/Project/des/subfolder_des1/
c:/Project/des//subfolder_des1/COM-EL-DES-0002-0.pdf
...
...
I'd like to create a second list which specifies the folder a value/path is associated with (e.g. das, des, and dga), but ignore subfolders. Any files in the Project folder would just have the value Project.
So resulting dataframe might look like:
Path col2
c:/Project/das das
c:/Project/des des
c:/Project/dga dga
c:/Project/des/subfolder_des1/ des
c:/Project/des/subfolder_des1/COM-EL-DES-0002-0.pdf des
c:/Project/randomfile.txt Project
c:/Project/dga/subfolder_dga1/ dga
...
...
Just unsure where to start, as I'm not sure I fully understand os.walk yet.
My code snippet:
def dir_tree(path):
dir_list = []
col2_list = []
for root, dirs, files in os.walk(path):
for d in dirs:
dir_list.append(os.path.join(root, d))
for f in files:
dir_list.append(os.path.join(root, f))
return dir_list, col2_list
def save_to_df(path):
dir_list, col2_list = dir_tree(path)
dir_tree_df = pd.DataFrame({"Path" : dir_list, "col2" : col2_list})
Edit: Something else to note, I'm only using dag, des etc as examples. I need to be able to run this script on any path, and it'll need to work out what the folder names are.
An updated script which might be doing what I want it to now:
def get_folder_name(path_str: str, source_directory: str) -> str:
path_replace = path_str.replace(source_directory, "")
path = Path(path_replace)
parts = path.parts
joined = os.path.join(source_directory, parts[1])
if os.path.isfile(joined):
return "root_files"
else:
return parts[1]