经常派得上用场,记录一下。
递归文件做一些操作
ruby
#encoding:utf-8
require 'pathname'
def recursive_enum_files(from_path)
from_path = Pathname.new(from_path)
raise ArgumentError,'must start at a directory.' unless from_path.directory?
from_path.enum_for(:find_files,from_path)
end
private def find_files(parent,&block)
parent.children.sort
parent.children.each do |child|
if child.directory?
find_files(child,&block)
else
yield child if block_given?
end
end
end
start_path = 'E:/abcdefg'
recursive_enum_files(start_path).each do |path|
puts (File.size?(path)/1024.0/1024.0/1024.0).round(2).to_s + 'GB => ' + path # 列出文件大小
end
对文件夹做一些操作
ruby
#encoding:utf-8
require 'pathname'
def recursive_enum_files(from_path)
from_path = Pathname.new(from_path)
raise ArgumentError,'must start at a directory.' unless from_path.directory?
from_path.enum_for(:find_files,from_path)
end
private def make_total(s)
return Proc.new { |i| s += i }
end
private def find_files(parent,&block)
n = make_total(0)
parent.children.each do |child|
if child.directory?
n.call(find_files(child,&block))
else
n.call(File.size?(child))
end
end
yield parent,n.call(0) if block_given?
n.call(0)
end
start_path = 'E:/abcdefg'
recursive_enum_files(start_path).each do |path,size|
puts (size/1024.0/1024.0/1024.0).round(2).to_s + 'GB => ' + path.to_s if size >= 1024*1024*1024*5 # 大于5GB
end