仅列出当前目录中的文件 [英] List files ONLY in the current directory

查看:51
本文介绍了仅列出当前目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Python, I only want to list all the files in the current directory ONLY. I do not want files listed from any sub directory or parent.

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

There do seem to be similar solutions out there, but they don't seem to work for me. Here's my code snippet:

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

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

Let's suppose I have 2 files, holygrail.py and Tim inside my current directory. I have a folder as well and it contains two files - let's call them Arthur and Lancelot - inside it. When I run the script, this is what I get:

holygrail.py
Tim
Arthur
Lancelot

我对 Holygrail.py 和 Tim 很满意.但我不想列出亚瑟和兰斯洛特这两个文件.

I am happy with holygrail.py and Tim. But the two files, Arthur and Lancelot, I do not want listed.

推荐答案

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

示例:

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

<小时>

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


But be careful while applying this to other directory, like

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

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

which would not work because f is not a full path but relative to the current dir.

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

Therefore, for filtering on another directory, do os.path.isfile(os.path.join(somedir, f))

(感谢因果关系的提示)

这篇关于仅列出当前目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆