1. 程式人生 > >讀取資料夾及子資料夾所有檔名並輸入到txt

讀取資料夾及子資料夾所有檔名並輸入到txt

#!/usr/bin/python
 
import os
 
 
def ListFilesToTxt(dir,file,wildcard,recursion):
    exts = wildcard.split(" ")
    files = os.listdir(dir)
    for name in files:
        fullname=os.path.join(dir,name)
        if(os.path.isdir(fullname) & recursion):
            ListFilesToTxt(fullname,file,wildcard,recursion)
        else:
            for ext in exts:
                if(name.endswith(ext)):
                    file.write(name + "\n")
                    break
 
def Test():
  dir="/home/robot_lcl/catkin_ws/src/beginner_tutorials/robot_bag/Asus/image_Asus"     #檔案路徑
  outfile="binaries.txt"                     #寫入的txt檔名
  wildcard = ".jpg .txt .exe .dll .lib"      #要讀取的檔案型別;
 
  file = open(outfile,"w")
  if not file:
    print ("cannot open the file %s for writing" % outfile)
 
  ListFilesToTxt(dir,file,wildcard, 1)
 
  file.close()
 
 
Test()