如何列出目录的所有文件?

编程入门 行业动态 更新时间:2024-10-24 04:33:48
本文介绍了如何列出目录的所有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

如何列出目录的所有文件?

本文发布于:2023-10-25 21:55:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528218.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   目录

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!