本文介绍了如何列出目录的所有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Python中列出目录的所有文件并将其添加到列表?
How can I list all files of a directory in Python and add them to a list?
推荐答案os.listdir() 将为您提供目录中的所有内容-文件和目录。
os.listdir() will get you everything that's in a directory - files and directories.
如果只需要 个文件,则可以使用 os.path :
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))]或者您可以使用 os.walk() ,它将产生两个列表用于访问的每个目录-为您拆分为文件和目录。如果您只想要顶层目录,则可以在第一次导入时打破它
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 break the first time it yields
from os import walk f = [] for (dirpath, dirnames, filenames) in walk(mypath): f.extend(filenames) break更多推荐
如何列出目录的所有文件?
发布评论