很多时候需要列出某目录下各个子目录中文件列表并保存到list.txt中,以便于以后遍历该子目录
在图片处理中,常用该方法处理图片目录
目录结构分为3级
rootdir
subdir1
pic1
pic2
subdir2
pic1
pic2
想要结果list.txt
rootdir 目录下
list.txt 内容为
subdir1
subdir2
subdir1/2目录下
list.txt内容为
pic1
pic2
代码为:
使用方法,把.py放到要提取的当前目录下即可
import os
rootdir=".";
folderlist=os.listdir(rootdir);
#print (folderlist)
rootlist=open(rootdir+"/list.txt",‘w‘)
for subfolder in folderlist:
#if subfolder[-3:]==".py":
#continue
print (subfolder)
subpath=rootdir+"/"+subfolder
if os.path.exists(subfolder+"/")==False:
print ("NO")
continue
rootlist.write(subfolder+"\n")
#print (subpath)
subfolderlist=os.listdir(subpath)
#print (subfolderlist)
listpath=subpath+"/list.txt"
listtxt=open(listpath,‘w‘)
for line in subfolderlist:
if line[-4:]==".txt":
continue
listtxt.write(line+"\n")
listtxt.close()
rootlist.close()