列出一个文件夹下的所有文件名(全路径)

来源:互联网 发布:淘宝店怎么找上家 编辑:程序博客网 时间:2024/05/16 12:57

需求:

列出一个文件夹下的所有文件的全路径文件名,

如果文件是文件夹,那么再次遍历这个文件夹的的所有文件名。直到遍历的文件不是文件夹为止。

这时输出文件的全路径名

分析:

可以用函数实现

1.函数参数1个,就是要遍历的文件夹的名字

2.遍历该文件夹

3.判断遍历的每一个文件的属性

4.如果该文件的属性为文件夹,那么回到第一步。

5.否则直接输出该文件在磁盘上的全路径名

用到的知识:

1.os.listdir(path)

2.os.path.isdir(filename)

需注意事情:

1.中文路径问题

源代码:

# -*- coding:utf-8 -*-__author__ = 'zengqiang.wang'import osimport sys#解决中文乱码问题def coding():    defaultencoding = 'utf-8'    if sys.getdefaultencoding() != defaultencoding:        reload(sys)        sys.setdefaultencoding(defaultencoding)#遍历文件夹并判断遍历的内容属性是否为文件夹def listFiles(path):    for filename in os.listdir(path):        newFilename = filename.decode('utf-8')        tempPath = path + '\\' + newFilename        if os.path.isdir(tempPath):            listFiles(tempPath)            #path = path + '\\'        else:            print path + '\\' + newFilenamecoding()#要遍历的文件夹名localPath = 'E:\我下载的软件'.decode('utf-8')paths = [localPath]for path in paths:    listFiles(path)


代码特色:

1.把编码问题和文件夹处理都封装为了函数。方便代码的重用。


阅读全文
0 0
原创粉丝点击