使用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')

结果如图

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值