import os
allpath=[]
allname=[]
def getallfile(path):
allfilelist=os.listdir(path)
# 遍历该文件夹下的所有目录或者文件
for file in allfilelist:
filepath=os.path.join(path,file)
# 如果是文件夹,递归调用函数
if os.path.isdir(filepath):
getallfile(filepath)
# 如果不是文件夹,保存文件路径及文件名
elif os.path.isfile(filepath):
allpath.append(filepath)
allname.append(file)
return allpath, allname
if __name__ == "__main__":
rootdir = "C:/rootdir"
files, names = getallfile(rootdir)
for file in files:
print(file)
print("-------------------------")
for name in names:
print(name)
以下是输出
C:/rootdir/aaa.txt
C:/rootdir/bbb.html
C:/rootdir/ccc.doc
C:/rootdir/dir1/aaaa.txt
C:/rootdir/dir1/bbbb.txt
C:/rootdir/dir1/cccc.txt
C:/rootdir/dir2/aaaaa.txt
C:/rootdir/dir2/bbbbb.txt
C:/rootdir/dir2/ccccc.txt
-------------------------
aaa.txt
bbb.html
ccc.doc
aaaa.txt
bbbb.txt
cccc.txt
aaaaa.txt
bbbbb.txt
ccccc.txt