【发布时间】:2021-01-11 01:41:08
【问题描述】:
我的目标 - 使用 OS walk 时仅列出 5 个条目。到目前为止,我只能获得使用 OS.Walk 找到的所有内容的列表,或者只列出一个条目。 (通过使用返回函数)
我的代码: 导入操作系统 导入子流程
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)),因为我相信搜索。
任何想法将不胜感激。感谢您的宝贵时间,
【问题讨论】:
-
从循环数到 5,然后
break。 -
有没有我可以使用的示例或我可以研究的关于使用 break 函数仅从我的函数返回 5 个字符串的链接?我用谷歌搜索了一些关于 break 的信息,但是所有的例子都显示了数字,而我的函数没有数字。它只是目录路径中的一串文件。 w3resource.com/python/python-break-continue.php