使用python遍历文件夹下的所有文件很方便,这里我来遍历文件夹,获得文件夹的父目录,文件夹名称以及所有文件名称,并且所有文件名存放在txr文档中。
import os
import os.path
rootdir="d:\image\slogan"
file = open("D:\image\path\path.txt","a")
for parent,dirnames,filenames in os.walk(rootdir):
for dirname in dirnames:
print "parent is:" + parent
print "dirname is" + dirname
for filename in filenames:
print "parent is:" + parent
print "filename is:" + filename
print "the full name of the file is:" + os.path.join(parent, filename)
file.write(filename)
file.write("\n")
file.close()
这样就把文件夹rootdir中的所有文件写入D:\image\path\path.txt中,还打印了文件夹信息。