如何在Python中列出目录中的所有文件并将其添加到列表中?
当前回答
dircache是“自2.6版以来已弃用:Python 3.0中已删除dircache模块。”
import dircache
list = dircache.listdir(pathname)
i = 0
check = len(list[0])
temp = []
count = len(list)
while count != 0:
if len(list[i]) != check:
temp.append(list[i-1])
check = len(list[i])
else:
i = i + 1
count = count - 1
print temp
其他回答
import os
os.listdir("somedirectory")
将返回“somedirectory”中所有文件和目录的列表。
dircache是“自2.6版以来已弃用:Python 3.0中已删除dircache模块。”
import dircache
list = dircache.listdir(pathname)
i = 0
check = len(list[0])
temp = []
count = len(list)
while count != 0:
if len(list[i]) != check:
temp.append(list[i-1])
check = len(list[i])
else:
i = i + 1
count = count - 1
print temp
从3.4版开始,有内置的迭代器,比os.listdir()高效得多:
pathlib:3.4版新增。
>>> import pathlib
>>> [p for p in pathlib.Path('.').iterdir() if p.is_file()]
根据PEP428,pathlib库的目的是提供一个简单的类层次结构来处理文件系统路径和用户对它们进行的常见操作。
os.scandir():3.5版新增。
>>> import os
>>> [entry for entry in os.scandir('.') if entry.is_file()]
注意,os.walk()使用os.scandir()而不是3.5版的os.listdir(),根据PEP471,它的速度提高了2-20倍。
让我也推荐阅读ShadowRanger在下面的评论。
我真的很喜欢adamk的回答,建议您使用来自同名模块的glob()。这允许您使用*s进行模式匹配。
但正如其他人在评论中指出的,glob()可能会被不一致的斜线方向绊倒。为了帮助实现这一点,我建议您在os.path模块中使用join()和expanduser()函数,也可以在os模块中使用getcwd()函数。
例如:
from glob import glob
# Return everything under C:\Users\admin that contains a folder called wlp.
glob('C:\Users\admin\*\wlp')
上面的情况很糟糕-路径已被硬编码,并且只能在Windows上在驱动器名称和硬编码到路径之间工作。
from glob import glob
from os.path import join
# Return everything under Users, admin, that contains a folder called wlp.
glob(join('Users', 'admin', '*', 'wlp'))
上面的方法效果更好,但它依赖于文件夹名Users,该文件夹名在Windows中常见,而在其他操作系统中不常见。它还依赖于具有特定名称admin的用户。
from glob import glob
from os.path import expanduser, join
# Return everything under the user directory that contains a folder called wlp.
glob(join(expanduser('~'), '*', 'wlp'))
这在所有平台上都非常有效。
另一个很好的例子,它可以在不同的平台上完美运行,并且做了一些不同的事情:
from glob import glob
from os import getcwd
from os.path import join
# Return everything under the current directory that contains a folder called wlp.
glob(join(getcwd(), '*', 'wlp'))
希望这些示例能帮助您了解在标准Python库模块中可以找到的一些函数的功能。
def list_files(path):
# returns a list of names (with extension, without full path) of all files
# in folder path
files = []
for name in os.listdir(path):
if os.path.isfile(os.path.join(path, name)):
files.append(name)
return files