问题:仅列出当前目录中的文件

在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)这两个文件。

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

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

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


回答 0

只需使用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))

(感谢因果关系的提示)

Just use os.listdir and os.path.isfile instead of os.walk.

Example:

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)].

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

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

(Thanks Causality for the hint)


回答 1

您可以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.

You can use os.listdir for this purpose. If you only want files and not directories, you can filter the results using os.path.isfile.

example:

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

or

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.

回答 2

import os

destdir = '/var/tmp/testdir'

files = [ f for f in os.listdir(destdir) if os.path.isfile(os.path.join(destdir,f)) ]
import os

destdir = '/var/tmp/testdir'

files = [ f for f in os.listdir(destdir) if os.path.isfile(os.path.join(destdir,f)) ]

回答 3

您可以使用os.scandir()。stdlib中的新功能从Python 3.5开始。

import os

for entry in os.scandir('.'):
    if entry.is_file():
        print(entry.name)

比快os.listdir()os.walk() 实施 os.scandir()

You can use os.scandir(). New function in stdlib starts from Python 3.5.

import os

for entry in os.scandir('.'):
    if entry.is_file():
        print(entry.name)

Faster than os.listdir(). os.walk() implements os.scandir().


回答 4

这可以用os.walk()完成

python 3.5.2测试;

import os
for root, dirs, files in os.walk('.', topdown=True):
    dirs.clear() #with topdown true, this will prevent walk from going into subs
    for file in files:
      #do some stuff
      print(file)

删除dirs.clear()行,并再次包含子文件夹中的文件。

参考更新;

os.walk记录在这里,并讨论了正在创建的三重列表和自上而下的效果。

此处记录的.clear()用于清空列表

因此,通过清除os.walk中的相关列表,您可以根据需要调整结果。

this can be done with os.walk()

python 3.5.2 tested;

import os
for root, dirs, files in os.walk('.', topdown=True):
    dirs.clear() #with topdown true, this will prevent walk from going into subs
    for file in files:
      #do some stuff
      print(file)

remove the dirs.clear() line and the files in sub folders are included again.

update with references;

os.walk documented here and talks about the triple list being created and topdown effects.

.clear() documented here for emptying a list

so by clearing the relevant list from os.walk you can effect its result to your needs.


回答 5

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

您可以通过以下方式改进此代码del dirs[:]

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

甚至更好,如果您可以将os.walk指向当前工作目录。

import os
cwd = os.getcwd()
for subdir, dirs, files in os.walk(cwd, topdown=True):
    del dirs[:]  # remove the sub directories.
    for file in files:
      do some stuff
      print file
import os
for subdir, dirs, files in os.walk('./'):
    for file in files:
      do some stuff
      print file

You can improve this code with del dirs[:]which will be like following .

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

Or even better if you could point os.walk with current working directory .

import os
cwd = os.getcwd()
for subdir, dirs, files in os.walk(cwd, topdown=True):
    del dirs[:]  # remove the sub directories.
    for file in files:
      do some stuff
      print file

回答 6

代替os.walk,只需使用os.listdir

instead of os.walk, just use os.listdir


回答 7

您可以使用pathlib模块。

from pathlib import Path
x = Path('./')
print(list(filter(lambda y:y.is_file(), x.iterdir())))

You can use the pathlib module.

from pathlib import Path
x = Path('./')
print(list(filter(lambda y:y.is_file(), x.iterdir())))

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。