收集的多個ruby遍歷文件夾代碼實例
更新時間:2015年05月22日 10:19:34 投稿:junjie
這篇文章主要介紹了收集的多個ruby遍歷文件夾代碼實例,本文總結(jié)了4個代碼片段,小編推薦最后一個方法,因為它很簡潔優(yōu)雅,需要的朋友可以參考下
一、遍歷文件夾下所有文件,輸出文件名
復(fù)制代碼 代碼如下:
def traverse_dir(file_path)
if File.directory? file_path
Dir.foreach(file_path) do |file|
if file !="." and file !=".."
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遍歷文件夾
復(fù)制代碼 代碼如下:
def get_file_list(path)
Dir.entries(path).each do |sub|
if sub != '.' && sub != '..'
if File.directory?("#{path}/#{sub}")
puts "[#{sub}]"
get_file_list("#{path}/#{sub}")
else
puts " |--#{sub}"
end
end
end
end
三、python如何遍歷一個目錄輸出所有文件名
復(fù)制代碼 代碼如下:
#coding=utf-8
'''
Created on 2014-11-14
@author: Neo
'''
import os
def GetFileList(dir, fileList):
newDir = dir
if os.path.isfile(dir):
fileList.append(dir.decode('gbk'))
elif os.path.isdir(dir):
for s in os.listdir(dir):
#如果需要忽略某些文件夾,使用以下代碼
#if s == "xxx":
#continue
newDir=os.path.join(dir,s)
GetFileList(newDir, fileList)
return fileList
list = GetFileList('D:\\workspace\\PyDemo\\fas', [])
for e in list:
print e
result:
復(fù)制代碼 代碼如下:
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
四、簡潔遍歷寫法
復(fù)制代碼 代碼如下:
import os
def iterbrowse(path):
for home, dirs, files in os.walk(path):
for filename in files:
yield os.path.join(home, filename)
for fullname in iterbrowse("/home/bruce"):
print fullname
您可能感興趣的文章:
相關(guān)文章
Ruby數(shù)組(Array)學(xué)習(xí)筆記
這篇文章主要介紹了Ruby數(shù)組(Array)學(xué)習(xí)筆記,本文講解了Ruby中數(shù)組的定義、數(shù)組元素的訪問、數(shù)組的操作、數(shù)組的運算等內(nèi)容,需要的朋友可以參考下2014-11-11Luhn算法學(xué)習(xí)及其Ruby版實現(xiàn)代碼示例
Luhn算法主要北用來進行數(shù)字驗證,尤其是卡號身份證號等,這里我們就來看一下Luhn算法學(xué)習(xí)及其Ruby版實現(xiàn)代碼示例:2016-05-05