Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

print/list only 5 entries from OS.Walk in python

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:UsersVGMPC2Documents	esting scriptssearch and print.py ===
name: test
E:NesJordan Vs Bird3 Point Contest.mp4
E:NesJordan Vs BirdSlam Dunk Contest.mp4
E:playlistAction&Adventuretest.xspf
E:playlistschedule test 2.xspf
E:SnesLufia IIThe Greatest Thieves.mp4
E:Symbolic playlistsNintendo Generation3 Point Contest.mp4
E:Symbolic playlistsNintendo GenerationSlam 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,

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...