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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…