Python遍历指定文件夹获取所有文件列表的方法
本文提供了一段Python代码,用于遍历指定目录并获取其中所有文件的完整路径列表。代码通过os.listdir逐层读取子目录,将文件路径存入列表后打印输出。适用于需要批量处理文件夹内文件的场景,代码中处理了路径编码及空目录判断,可直接参考使用。
下面分享一段使用Python语言获取指定文件夹内所有文件的具体实现代码,供读者参考学习。
#!/user/bin/python
# -*- coding:utf8 -*-
import Basic
import os
#####################################################
######## Input ####
folder = "D:\\安装包"
folder = folder.encode("gbk")
######## Global ####
fileList = []
allFiles = []
tree = []
level = 0
#####################################################
try:
if folder is None or len(folder) == 0:
folder = os.curdir
if os.path.isdir(folder):
childFile = os.listdir(folder)
fileList = ["%s" % (folder+os.path.sep+f) for f in childFile]
node = {'file':folder, 'level':level}
tree.append(node)
while fileList is not None and len(fileList) > 0:
allFiles.append(""+fileList[0])
if os.path.isdir(fileList[0]):
childFile = os.listdir(fileList[0])
if childFile is not None and len(childFile) > 0:
fileList = fileList + ["%s" % (fileList[0]+os.path.sep+ft) for ft in childFile]
else:
pass
else:
pass
fileList.pop(0)
print "\n".join(["%s" % f for f in allFiles])
else:
print 'not folder, no child'
except Exception,x:
print x
以上内容即为本文介绍的全部代码与说明,希望能为读者的编程学习提供便利,同时也欢迎持续关注本站以获取更多技术资源。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













