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

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

问题描述

如何在 Python 中列出目录的所有文件并将它们添加到 list 中?

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() 它将为它访问的每个目录生成两个列表 - 分成文件dirs 给你.如果你只想要顶级目录,你可以在第一次产生时中断

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

或者更短:

from os import walk

filenames = next(walk(mypath), (None, None, []))[2]  # [] if no file

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

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