当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Os.walk upon reaching a new folder

问题描述:

I wrote this script to make M3u files for my music collection so i can open just one file and listen to a whole cd or w.e.

What my script does ATM is: make an M3u file for every song within the CWD and the underlaying folders in one M3u file which he places in the CWD.

But i want to also make an M3u file in every sub folder of the CWD.

So upon reaching a subfolder it should open a file with the filename of the CWD and place all the names of that folder into that file and save the file as: "CWD".M3u

import os,sys

folder_name=os.path.basename(os.getcwd())

folder=os.getcwd()

ext3=['.mp3','.Mp3']

file=open('%s.m3u'%(folder_name),'w')

for root, dirs, files in os.walk(folder):

for x in files:

if x[-4:] in ext3:

print(root+'\\'+x)

file.write('%s\%s\n'%(root,x))

file.close()

if not x[-4:] in ext3:

print("List is empty.")

网友答案:

I think this is what you're looking for. os.walk is actually recursive, so your code could be made to work just by opening a new .m3u file in the directly currently being walked over on every iteration of the outer for loop:

import os

exts = ('.mp3','.Mp3')

for root, dirs, files in os.walk(os.getcwd()):
    m3uname = os.path.basename(root)
    with open("{}.m3u".format(os.path.join(root, m3uname)), 'w') as outfile:
        for f in files:
            if f.endswith(exts):
                outfile.write('{}\n'.format(os.path.join(root, f)))
分享给朋友:
您可能感兴趣的文章:
随机阅读: