Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

python 3.x - Directory to Variable

I have this directory structure, and would only like to take the 7rd level as a variable

D:homeuserarcmusicMP3AA_Day_To_RememberAlbum1
D:homeuserarcmusicMP3AAbrooAlbum1
D:homeuserarcmusicMP3AAbrooAlbum2
D:homeuserarcmusicMP3AACDCAlbum1

D:homeuserarcmusicMP3BBeatsteaksAlbum1
D:homeuserarcmusicMP3BBee_GeesAlbum1
D:homeuserarcmusicMP3BBell_Book_and_CandleAlbum1
etc..

I would now like to take the artist name into a variable.

example ACDC, Beatsteaks, Abroo etc

import os
main_path = r'D:homeuserarcmusicMP3'


def main():
    for root, dirs, files in os.walk(main_path):
        for dir in dirs:
            print(dirs)






['A', 'B']
['A', 'B']
['Abroo', 'ACDC', 'A_Day_To_Remember']
['Abroo', 'ACDC', 'A_Day_To_Remember']
['Abroo', 'ACDC', 'A_Day_To_Remember']
['Album1']
['Album2']
['Album1']
etc...

but so here everything is output, how can I narrow it down to the artist?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this

import os
main_path = r'D:homeuserarcmusicMP3'

def main():
  for root, dirs, files in os.walk(main_path):
    depth = 0
    for dir in dirs:
        depth = depth + 1
        if depth == 1:
          print(dir)

main()

please adjust 1 in if depth == 1 to appropriate value


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...