python中可以用os.walk来遍历某个文件夹中所有文件夹和文件。
例1:
import os
filePath = 'C:/Users/admin/Desktop/img'
for dirpath, dirnames, filenames in os.walk(filePath):
print(dirpath, dirnames, filenames)
输出结果:
例2:
import os
filePath = 'C:\\Users\\admin\\Desktop\\img'
for dirpath, dirnames, filenames in os.walk(filePath):
path = [os.path.join(dirpath, names) for names in filenames]
print(path)
输出结果:
例3,统计某个文件夹下所有文件(包括子文件夹中的文件)的数目:
import os
dir_path = r'E:\CS\action_research\cmu_mocap\wenjun\subset_split\split3'
file = []
for dirpath, dirnames, filenames in os.walk(dir_path):
file = file + [os.path.join(dirpath, names) for names in filenames]
print('file count:', len(file))
输出结果: file count: 221
例4,读取某个文件夹下所有文件(包括子文件夹中的文件):
假设这些文件都是txt文件。
import numpy as np
import os
dir_path = r'E:\CS\action_research\cmu_mocap\wenjun\subset_split\split1'
file = []
for dirpath, dirnames, filenames in os.walk(dir_path):
for name in filenames:
file.append(np.loadtxt(os.path.join(dirpath, name), dtype=np.float32, delimiter=','))