Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

python - 如何列出目录的所有文件?(How do I list all files of a directory?)

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

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

  ask by duhhunjonn translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(os.listdir()将为您提供目录中的所有内容-文件和目录。)

If you want just files, you could either filter this down using os.path :

(如果只需要文件,则可以使用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.

(或者您可以使用os.walk() ,它将为它访问的每个目录生成两个列表-为您拆分为文件和目录。)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...