簡體   English   中英

Python遞歸遍歷所有子目錄,並將文件名寫入輸出文件

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

我想遞歸地遍歷根文件夾中的所有子目錄,並將所有文件名寫入輸出文件。 然后在每個子目錄中,在子目錄中創建一個新的輸出文件,然后遞歸地遍歷其子目錄,並將文件名附加到新的輸出文件中。

因此,在下面的示例中,它應該在Music文件夾下創建Music.m3u8文件,並遞歸遍歷所有子目錄,並將每個子目錄中的所有文件名添加到Music.m3u8文件中。 然后在Rock文件夾中,創建一個Rock.m3u8文件,並遞歸遍歷Rock文件夾中的所有子目錄,並將所有文件名添加到Rock.m3u8的每個子目錄中。 最后,在每個Album文件夾中,使用其文件夾中的文件名創建Album1.m3u8,Album2.m3u8等。 如何在python3.6中做到這一點?

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

這就是我所擁有的,但是僅將每個文件夾的文件名添加到輸出文件中,而不以遞歸方式添加到根輸出文件中。

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')

您正在with open(list_file_path, 'w') as list_file:每次通過外循環。 但是您不會創建或寫入任何頂級文件,因此,您當然沒有一個。 如果需要一個,則必須顯式創建它。 例如:

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')

(我只是在猜測您在該根文件中實際想要的內容;您大概知道答案了,不必猜測…)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM