如何列出目录的所有文件? [英] How to list all files of a directory?
问题描述
如何在python中列出目录的所有文件并将其添加到列表中?
os.listdir()
将让您的目录中的所有内容 - 文件和目录。
如果您想要只是文件,您可以使用 os进行过滤.path
:
从os import listdir
从os.path import isfile,join
onlyfiles = [f for list in d(mypath)if isfile(join(mypath,f))]
或者你可以使用 os.walk()
,它将为其访问的每个目录产生两个列表 - 为您分解为文件和目录。如果您只想要顶级目录,您可以第一次从os import walk
$ b中获得
$ / code $ c
$ / pre>
最后,如该示例所示,将一个列表添加到另一个列表中,您可以使用 .extend()
或
>>> q = [1,2,3]
>>> w = [4,5,6]
>>> q = q + w
>>>> q
[1,2,3,4,5,6]
个人而言喜欢 .extend()
How can I list all files of a directory in python and add them to a list?
解决方案 os.listdir()
will get you everything that's in a directory - files and directories.
If you want just files, you could either filter this down using os.path
:
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
or you could use os.walk()
which will yield two lists for each directory it visits - splitting into files and dirs for you. If you only want the top directory you can just break the first time it yields
from os import walk
f = []
for (dirpath, dirnames, filenames) in walk(mypath):
f.extend(filenames)
break
And lastly, as that example shows, adding one list to another you can either use .extend()
or
>>> q = [1, 2, 3]
>>> w = [4, 5, 6]
>>> q = q + w
>>> q
[1, 2, 3, 4, 5, 6]
Personally, I prefer .extend()
这篇关于如何列出目录的所有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!