使用python遍历文件夹内文件,并保存路径于文本文件中

参考了https://www.cnblogs.com/Lazycat1206/p/12382864.html

文件夹结构为

D:\CODES\KEYAN\PEIDIAN\DISCHARGE
├─corona_discharge
├─float_discharge
├─interference
├─internal_discharge
└─surface_discharge

每个文件夹内含有100个CSV文件,共计500个CSV文件

以下为代码

import os

dirPath = "d:\\Codes\\keyan\\peidian\\discharge"
resultFile = "d:\\Codes\\keyan\\peidian\\discharge_csv_label.txt"
fresultFile = open(resultFile, 'w') # 打开文件

csvLabel = os.listdir(dirPath) # 得到标签
for i in range(5):
    labelDirPath = dirPath + "\\" + csvLabel[i]
    gDirPath = os.walk(labelDirPath) # 文件名迭代器

    for root, dirs, files in gDirPath:
        for f in files:
            fresultFile.write(labelDirPath + "\\" + f + ' ' + csvLabel[i] + '\n')

结果如图

使用python遍历文件夹内文件,并保存路径于文本文件中_第1张图片

每个文件路径后面都加上了标签,即所在子文件夹的名字。

你可能感兴趣的:(ML)