仅列出当前目录中的文件

新手上路,请多包涵

在 Python 中,我只想列出当前目录中的所有文件。我不希望从任何子目录或父目录中列出文件。

那里似乎确实有类似的解决方案,但它们似乎对我不起作用。这是我的代码片段:

 import os
for subdir, dirs, files in os.walk('./'):
    for file in files:
      do some stuff
      print file

假设我的当前目录中有 2 个文件,holygrail.py 和 Tim。我也有一个文件夹,其中包含两个文件——我们称它们为 Arthur 和 Lancelot——在里面。当我运行脚本时,这就是我得到的:

 holygrail.py
Tim
Arthur
Lancelot

我对 Holygrail.py 和 Tim 很满意。但是我不想列出 Arthur 和 Lancelot 这两个文件。

原文由 slam_duncan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 342
2 个回答

只需使用 os.listdiros.path.isfile 而不是 os.walk

例子:

 import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
    # do something


但是在将其应用于其他目录时要小心,例如

files = [f for f in os.listdir(somedir) if os.path.isfile(f)]

这不起作用,因为 f 不是完整路径,而是相对于当前目录。

因此,要过滤另一个目录,请执行 os.path.isfile(os.path.join(somedir, f))

(感谢 因果 的提示)

原文由 sloth 发布,翻译遵循 CC BY-SA 4.0 许可协议

为此,您可以使用 os.listdir 。如果您只需要 文件 而不需要 _目录_,则可以使用 os.path.isfile 过滤结果。

例子:

 files = os.listdir(os.curdir)  #files and directories

要么

files = filter(os.path.isfile, os.listdir( os.curdir ) )  # files only
files = [ f for f in os.listdir( os.curdir ) if os.path.isfile(f) ] #list comprehension version.

原文由 mgilson 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题