python 文件夹递归

import os
path = "F:/new" #文件夹目录
datas = []
def eachFile(filepath):
fileNames = os.listdir(filepath) # 获取当前路径下的文件名,返回List
for file in fileNames:
newDir = filepath + '/' + file # 将文件命加入到当前文件路径后面
# print(newDir)
# if os.path.isdir(newDir): # 如果是文件夹
if os.path.isfile(newDir): # 如果是文件
if os.path.splitext(newDir)[1] == ".txt": # 判断是否是txt
f = open(newDir)
str = ""
for line in f.readlines():
str = str + line # 读文件
datas.append(str)
else:
eachFile(newDir) #如果不是文件,递归这个文件夹的路径

if __name__ == "__main__":
eachFile(path)
print(datas)
————————————————
版权声明:本文为CSDN博主「Young_Simple」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/jxx_1_112136/article/details/82887608

原文地址:https://www.cnblogs.com/ouousan/p/12375831.html