【问题标题】:print/list only 5 entries from OS.Walk in python在 python 中仅打印/列出 OS.Walk 中的 5 个条目
【发布时间】: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

标签: python list os.walk


【解决方案1】:

试试这个:

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

【讨论】:

  • 就是这样!!我知道这与 python 使用的 [] 列表有关。 (对不起 - 菜鸟。大声笑)我只是不知道如何在这种情况下使用它。 (代码学院没有帮助。大声笑)非常感谢!
猜你喜欢
  • 1970-01-01
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 2013-03-29
相关资源
最近更新 更多