Ruby递归目录文件的又一种方法

经常派得上用场,记录一下。

递归文件做一些操作

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
相关推荐
是Dream呀29 分钟前
Python从0到100(八十六):神经网络-ShuffleNet通道混合轻量级网络的深入介绍
网络·python·神经网络
zxfeng~30 分钟前
深度学习之“线性代数”
人工智能·python·深度学习·线性代数
沈韶珺40 分钟前
Visual Basic语言的云计算
开发语言·后端·golang
沈韶珺1 小时前
Perl语言的函数实现
开发语言·后端·golang
嘻嘻哈哈的zl1 小时前
初级数据结构:栈和队列
c语言·开发语言·数据结构
wjs20241 小时前
MySQL 插入数据指南
开发语言
美味小鱼1 小时前
Rust 所有权特性详解
开发语言·后端·rust
叫我DPT1 小时前
Python 中 `finally` 的执行时机与 `return` 的微妙关系
python
Bluesonli1 小时前
第 1 天:UE5 C++ 开发环境搭建,全流程指南
开发语言·c++·ue5·虚幻·unreal engine
wjs20241 小时前
三路排序算法
开发语言