如何列出目录的所有文件? [英] How do I list all files of a directory?

查看:100
本文介绍了如何列出目录的所有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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

这篇关于如何列出目录的所有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆