-1

My Goal - To list only 5 entries when using OS walk. So far I have only been able to get a list of everything that I find using OS.Walk or only list one entry. (By using the return function)

My code: import os import subprocess

def playmusic(name):
    for root, dirs, files in os.walk('E:\\', followlinks=True):
        for file in files:
            if name in file:
                vlc='C:/Program Files/VideoLAN/VLC/vlc.exe'
                music=str(os.path.join(root,file))
                print(music)
                #subprocess.Popen([vlc, music])
                #return
    print("Finish")
    input()
try:
    s=raw_input("name: ")
    playmusic(s)
except Exception as e:
    print(e)
    print("Error")

The Results:

=== RESTART: C:\Users\VGMPC2\Documents\testing scripts\search and print.py ===
name: test
E:\Nes\Jordan Vs Bird\3 Point Contest.mp4
E:\Nes\Jordan Vs Bird\Slam Dunk Contest.mp4
E:\playlist\Action&Adventuretest.xspf
E:\playlist\schedule test 2.xspf
E:\Snes\Lufia II\The Greatest Thieves.mp4
E:\Symbolic playlists\Nintendo Generation\3 Point Contest.mp4
E:\Symbolic playlists\Nintendo Generation\Slam Dunk Contest.mp4
Finish

My code

If there is any way to only show 5 instead of the whole list that would be great! I tried using len() but I was having trouble figuring out how to use it with the os walk search. I would say the biggest thing is the music=str(os.path.join(root,file)) as that does the search I believe.

Any ideas would be appreciated. Thank you for your time,

  • 1
    Count to 5 and then `break` from the loop. – zvone Jan 11 '21 at 01:42
  • Is there an example I can use or a link that I can research regarding using the break function to only return 5 strings back from my function? I googled it and got back some information regarding break but all of the examples show numbers and my function doesn't have numbers. Its just a string of files in a directory path. https://www.w3resource.com/python/python-break-continue.php –  Jan 11 '21 at 01:51

1 Answers1

0

Try this:

def playmusic(name):
    for root, dirs, files in os.walk('E:\\', followlinks=True):
        for file in files[0:5]: #You show the first five only
            if name in file:
                vlc='C:/Program Files/VideoLAN/VLC/vlc.exe'
                music=str(os.path.join(root,file))
                print(music)
                #subprocess.Popen([vlc, music])
                #return
    print("Finish")
    input()
try:
    s=raw_input("name: ")
    playmusic(s)
except Exception as e:
    print(e)
    print("Error")
Synthase
  • 5,849
  • 2
  • 12
  • 34
  • THIS WAS IT!! I knew it had something to do with the [] list thing that python uses. (Sorry - noob. lol) I just didn't know how to use it in this situation. (Code academy doesn't help. lol) Thanks a TON! –  Jan 11 '21 at 01:58