从OS.Walk中仅打印/列出OS中的5个条目 [英] print/list only 5 entries from OS.Walk in python
问题描述
我的目标-使用OS Walk时仅列出5个条目.到目前为止,我只能获得使用OS.Walk找到的所有内容的列表,或者仅列出一个条目.(通过使用return函数)
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")
结果:
=== 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
如果有什么办法只显示5个而不是整个列表,那将是很棒的!我尝试使用len(),但是在弄清楚如何在os walk搜索中使用它时遇到了麻烦.我会说最大的事情就是 music = str(os.path.join(root,file))
,因为我相信该搜索会如此.
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,
推荐答案
尝试一下:
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")
这篇关于从OS.Walk中仅打印/列出OS中的5个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!