Python - 如何在 os.listdir 中查找文件和跳过目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22207936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - how to find files and skip directories in os.listdir
提问by Bartee
I use os.listdirand it works fine, but I get sub-directories in the list also, which is not what I want: I need only files.
我使用os.listdir并且它工作正常,但我也在列表中获得了子目录,这不是我想要的:我只需要文件。
What function do I need to use for that?
我需要为此使用什么功能?
I looked also at os.walkand it seems to be what I want, but I'm not sure of how it works.
我也看了看os.walk,这似乎是我想要的,但我不确定它是如何工作的。
采纳答案by Martijn Pieters
You need to filter out directories; os.listdir()lists all namesin a given path. You can use os.path.isdir()for this:
您需要过滤掉目录;os.listdir()列出给定路径中的所有名称。您可以os.path.isdir()为此使用:
basepath = '/path/to/directory'
for fname in os.listdir(basepath):
path = os.path.join(basepath, fname)
if os.path.isdir(path):
# skip directories
continue
os.walk()does the same work under the hood; unless you need to recurse down subdirectories, you don't need to use os.walk()here.
os.walk()在引擎盖下做同样的工作;除非你需要递归子目录,否则你不需要在os.walk()这里使用。
回答by nagylzs
for fname in os.listdir('.'):
if os.path.isdir(fname):
pass # do your stuff here for directory
else:
pass # do your stuff here for regular file
回答by Alex Thornton
Here is a nice little one-liner in the form of a list comprehension:
这是一个以列表理解形式出现的漂亮的单行代码:
[f for f in os.listdir(your_directory) if os.path.isfile(os.path.join(your_directory, f))]
This will returna listof filenames within the specified your_directory.
这将return是list指定your_directory.
回答by SixSense
import os
directoryOfChoice = "C:\" # Replace with a directory of choice!!!
filter(os.path.isfile, os.listdir(directoryOfChoice))
P.S: os.getcwd()returns the current directory.
PS:os.getcwd()返回当前目录。

