Python Forum
How to combine file names into a list from multiple directories?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to combine file names into a list from multiple directories?
#2
I hope this will help:
#!/usr/bin/python3
import os, pprint

path = "test/"
file_list = {}

for dirname in os.listdir(path):
    print("dir:", dirname)
    for root,dirs,files in os.walk(path + dirname):
        for filename in files:
            print("file:", filename)
            if filename not in file_list:
                file_list[filename]  = []
            file_list[filename].append(os.path.join(root, filename))

print()
pprint.pprint(file_list)
Output:
dir: folder2 file: filea file: fileb file: filec dir: folder3 file: filea file: fileb file: filec dir: folder1 file: filea file: fileb file: filec {'filea': ['test/folder2/filea', 'test/folder3/filea', 'test/folder1/filea'], 'fileb': ['test/folder2/fileb', 'test/folder3/fileb', 'test/folder1/fileb'], 'filec': ['test/folder2/filec', 'test/folder3/filec', 'test/folder1/filec']}
Reply


Messages In This Thread
RE: How to combine file names into a list from multiple directories? - by heiner55 - Jun-25-2019, 05:33 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Organization of project directories wotoko 3 559 Mar-02-2024, 03:34 PM
Last Post: Larz60+
  Navigating file directories and paths inside Jupyter Notebook Mark17 5 865 Oct-29-2023, 12:40 PM
Last Post: Mark17
  How can i combine these two functions so i only open the file once? cubangt 4 969 Aug-14-2023, 05:04 PM
Last Post: snippsat
  Listing directories (as a text file) kiwi99 1 907 Feb-17-2023, 12:58 PM
Last Post: Larz60+
  Find duplicate files in multiple directories Pavel_47 9 3,387 Dec-27-2022, 04:47 PM
Last Post: deanhystad
  rename same file names in different directories elnk 0 767 Nov-04-2022, 05:23 PM
Last Post: elnk
  How to combine multiple column values into 1? cubangt 15 3,140 Aug-11-2022, 08:25 PM
Last Post: cubangt
  I need to copy all the directories that do not match the pattern tester_V 7 2,652 Feb-04-2022, 06:26 PM
Last Post: tester_V
  Functions to consider for file renaming and moving around directories cubangt 2 1,856 Jan-07-2022, 02:16 PM
Last Post: cubangt
  How to combine multiple rows of strings into one using pandas? shantanu97 1 3,234 Aug-22-2021, 05:26 AM
Last Post: klllmmm

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020