Python 批量读取文件名并写入txt中


[python]  view plain  copy
  1. #coding=utf-8  
  2. import sys  
  3. import os, glob  
  4.   
  5. reload(sys)  
  6. sys.setdefaultencoding('utf-8')  
  7.   
  8. #输出路径,自行修改  
  9. TxtPath="C://Users//yupu//Desktop//f.txt"  
  10.   
  11. def BFS_Dir(dirPath, dirCallback = None, fileCallback = None):  
  12.     queue = []  
  13.     ret = []  
  14.     f=open(TxtPath,'w')    # r只读,w可写,a追加  
  15.     queue.append(dirPath);  
  16.     while len(queue) > 0:  
  17.         tmp = queue.pop(0)  
  18.         if(os.path.isdir(tmp)):  
  19.             ret.append(tmp)  
  20.             for item in os.listdir(tmp):  
  21.                 queue.append(os.path.join(tmp, item))  
  22.             if dirCallback:  
  23.                 dirCallback(tmp)  
  24.         elif(os.path.isfile(tmp)):  
  25.             ret.append(tmp)  
  26.             if fileCallback:  
  27.                 mPath , ext = os.path.splitext(tmp)  
  28.                 names = os.path.split(mPath)  
  29.                 if(ext==".meta"):  
  30.                     continue  
  31.                 else:  
  32.                    print names[1]  
  33.                    f.write(names[1])  
  34.                    f.write('\n')  
  35.                    fileCallback(tmp)  
  36.     f.close()  
  37.     return ret  
  38.   
  39. def printDir(dirPath):  
  40.     print "dir: " + dirPath  
  41.   
  42. def printFile(dirPath):  
  43.     print "file: " + dirPath  
  44.   
  45. if __name__ == '__main__':  
  46.     while True:  
  47.         path = raw_input("Path:")  
  48.         try:  
  49.             b = BFS_Dir(path , printDir, printFile)  
  50.             print ("\r\n          *******\r\n"+"*********Done*********"+"\r\n          **********\r\n")  
  51.         except:  
  52.             print "Unexpected error:", sys.exc_info()  
  53.         raw_input('press enter key to rehandle')  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值