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
JavaScript
x
18
18
1
def playmusic(name):
2
for root, dirs, files in os.walk('E:\', followlinks=True):
3
for file in files:
4
if name in file:
5
vlc='C:/Program Files/VideoLAN/VLC/vlc.exe'
6
music=str(os.path.join(root,file))
7
print(music)
8
#subprocess.Popen([vlc, music])
9
#return
10
print("Finish")
11
input()
12
try:
13
s=raw_input("name: ")
14
playmusic(s)
15
except Exception as e:
16
print(e)
17
print("Error")
18
The Results:
JavaScript
1
11
11
1
=== RESTART: C:UsersVGMPC2Documentstesting scriptssearch and print.py ===
2
name: test
3
E:NesJordan Vs Bird3 Point Contest.mp4
4
E:NesJordan Vs BirdSlam Dunk Contest.mp4
5
E:playlistAction&Adventuretest.xspf
6
E:playlistschedule test 2.xspf
7
E:SnesLufia IIThe Greatest Thieves.mp4
8
E:Symbolic playlistsNintendo Generation3 Point Contest.mp4
9
E:Symbolic playlistsNintendo GenerationSlam Dunk Contest.mp4
10
Finish
11
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,
Advertisement
Answer
Try this:
JavaScript
1
18
18
1
def playmusic(name):
2
for root, dirs, files in os.walk('E:\', followlinks=True):
3
for file in files[0:5]: #You show the first five only
4
if name in file:
5
vlc='C:/Program Files/VideoLAN/VLC/vlc.exe'
6
music=str(os.path.join(root,file))
7
print(music)
8
#subprocess.Popen([vlc, music])
9
#return
10
print("Finish")
11
input()
12
try:
13
s=raw_input("name: ")
14
playmusic(s)
15
except Exception as e:
16
print(e)
17
print("Error")
18