收集的多个ruby遍历文件夹代码实例
一、遍历文件夹下所有文件,输出文件名
deftraverse_dir(file_path) ifFile.directory?file_path Dir.foreach(file_path)do|file| iffile!="."andfile!=".." traverse_dir(file_path+"/"+file) end end else puts"File:#{File.basename(file_path)},Size:#{File.size(file_path)}" end end traverse_dir('D:/apache-tomcat')
二、ruby遍历文件夹
defget_file_list(path) Dir.entries(path).eachdo|sub| ifsub!='.'&&sub!='..' ifFile.directory?("#{path}/#{sub}") puts"[#{sub}]" get_file_list("#{path}/#{sub}") else puts" |--#{sub}" end end end end
三、python如何遍历一个目录输出所有文件名
#coding=utf-8 ''' Createdon2014-11-14 @author:Neo ''' importos defGetFileList(dir,fileList): newDir=dir ifos.path.isfile(dir): fileList.append(dir.decode('gbk')) elifos.path.isdir(dir): forsinos.listdir(dir): #如果需要忽略某些文件夹,使用以下代码 #ifs=="xxx": #continue newDir=os.path.join(dir,s) GetFileList(newDir,fileList) returnfileList list=GetFileList('D:\\workspace\\PyDemo\\fas',[]) foreinlist: printe
result:
D:\workspace\PyDemo\fas\file1\20141113\a.20141113-1100.log D:\workspace\PyDemo\fas\file1\20141113\a.20141113-1101.log D:\workspace\PyDemo\fas\file1\20141113\a.20141113-1140.log D:\workspace\PyDemo\fas\file2\20141113\a.20141113-1100.log D:\workspace\PyDemo\fas\file2\20141113\a.20141113-1101.log D:\workspace\PyDemo\fas\file2\20141113\a.20141113-1140.log
四、简洁遍历写法
importos defiterbrowse(path): forhome,dirs,filesinos.walk(path): forfilenameinfiles: yieldos.path.join(home,filename) forfullnameiniterbrowse("/home/bruce"): printfullname