H5W3
当前位置:H5W3 > 问答 > 正文

How do I list all files of a directory?

This question’s answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.

How can I list all files of a directory in Python and add them to a list?

Answer

os.listdir() will get you everything that’s in a directory – files and directories.

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))]

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 just break the first time it yields

from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break

本文地址:H5W3 » How do I list all files of a directory?

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址