遍历目录,列出下面所有文件名(带目录名),并且把所有文件名存入listfile列表,最后显示列表的内容。
# -*- coding: cp936 -*-
import os,sys
def listdir(dir):
fielnum = 0
listfile = []
list = os.listdir(dir) #列出目录下的所有文件和目录
for line in list:
filepath = os.path.join(dir,line)
if os.path.isdir(filepath): #如果filepath是目录,则再列出该目录下的所有文件
for li in os.listdir(filepath):
print filepath + li
listfile.append(filepath + li)
fielnum = fielnum + 1
elif os.path: #如果filepath是文件,直接列出文件名
fielnum = fielnum + 1
print filepath + line
listfile.append(filepath + line)
print ('文件总数是'+ str(fielnum))
print listfile
#dir = raw_input('please input the path:')
dir = "D:\\tools"
listdir(dir)