Home > Mobile >  Tring to get one item from list
Tring to get one item from list

Time:09-23

Hello i'm trying to get one item from list but idk to do that

this is my code:

import os

for root, dirs, files in os.walk("/media/archsohee/Music/"):
    for file in files:
        if file.endswith(".flac"):
            fldr = (os.path.join(file))
            lk = fldr.split(',')[0]
            print(lk)
        elif file.endswith(".mp3"):
            print(os.path.join(file))

The output:

08 - Mac DeMarco - Dreams from Yesterday.flac
03 - Mac DeMarco - Baby You're Out.flac
01 - itssvd - Love Again.flac
Save Yourself (Japanese Version) - ONE OK ROCK.flac
03 - Philip Pors Jepsen - Trust Nobody.flac
04 - Mac DeMarco - For the First Time.flac
09 - Arctic Monkeys - Why'd You Only Call Me When You're High-.flac
10 - Mac DeMarco - Go Easy.flac
11 - Mac DeMarco - On the Level.flac
04 - Mac DeMarco - Let Her Go.flac
09 - Mac DeMarco - Chamber Of Reflection.flac
06 - Mac DeMarco - Still Beating.flac
02 - Philip Pors Jepsen - My Sin.flac

i want to get one of them like "11 - Mac DeMarco - On the Level.flac"

CodePudding user response:

To get an item from a list you need a list. Your code is just printing the file name.

First, create a list:

import os 

path = "media/archsohee/Music"
file_list = [] #create an empty list that we'll append our files too.

for root, dirs, files in os.walk(path):
    for file in files:
        if '.flac' in file: #if filename contains ".flac" add it to our list.
            file_list.append(file)

print(file_list)

Then... perform an operation on the list:

From here, you can perform operations on the list. For example get the first item in the list or create a new list with only songs by Mac DeMarco.

print(file_list[0]) #this returns the first item in the list

mac_demarco_songs = [file for file in file_list if 'Mac DeMarco' in file] #note that "Mac Demarco" is case sensitive.
print(mac_demarco_songs) #prints our list of Mac DeMarco songs.
  • Related