bayman
bayman

Reputation: 1719

Python recursively traverse through all subdirs and write the filenames to output file

I want to recursively traverse through all subdirs in a root folder and write all filenames to an output file. Then in each subdir, create a new output file inside the subdir and recursively traverse through its subdirs and append the filename to the new output file.

So in the example below, under the Music folder it should create a Music.m3u8 file and recursively traverse all subdirs and add all filenames in each subdir to the Music.m3u8 file. Then in Rock folder, create a Rock.m3u8 file and recursively traverse all subdirs within the Rock folder and add all filenames in each subdirs in Rock.m3u8. Finally in each Album folder, create Album1.m3u8, Album2.m3u8, etc with the filenames in its folder. How can I do this in python3.6?

Music
....Rock
........Album1
........Album2
....Hip-Hop
........Album3
........Album4

This is what I have but only adds the filenames of each folder to an output file but doesn't recursively adds to the root output file.

import os

rootdir = '/Users/bayman/Music'
ext = [".mp3", ".flac"]
for root, dirs, files in os.walk(rootdir):
    path = root.split(os.sep)

    if any(file.endswith(tuple(ext)) for file in files):
        m3ufile = str(os.path.basename(root))+'.m3u8'
        list_file_path = os.path.join(root, m3ufile)
        with open(list_file_path, 'w') as list_file:
            list_file.write("#EXTM3U\n")
            for file in sorted(files):
                if file.endswith(tuple(ext)):
                    list_file.write(file + '\n')

Upvotes: 0

Views: 100

Answers (1)

abarnert
abarnert

Reputation: 365657

You're doing with open(list_file_path, 'w') as list_file: each time through the outer loop. But you're not creating, or writing to, any top-level file, so of course you don't get one. If you want one, you have to explicitly create it. For example:

rootdir = '/Users/bayman/Music'
ext = [".mp3", ".flac"]
with open('root.m3u', 'w') as root_file:
    root_file.write("#EXTM3U\n")
    for root, dirs, files in os.walk(rootdir):
        path = root.split(os.sep)
        if any(file.endswith(tuple(ext)) for file in files):
            m3ufile = str(os.path.basename(root))+'.m3u8'
            list_file_path = os.path.join(root, m3ufile)
            with open(list_file_path, 'w') as list_file:
                list_file.write("#EXTM3U\n")
                for file in sorted(files):
                    if file.endswith(tuple(ext)):
                        root_file.write(os.path.join(root, file) + '\n')
                        list_file.write(file + '\n')

(I'm just guessing at what you actually want in that root file here; you presumably know the answer to that and don't have to guess…)

Upvotes: 1

Related Questions