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
相关推荐
2601_9498180925 分钟前
Vector从入门到应用(C++ STL动态数组万字全解
开发语言·c++
尼恩久38 分钟前
记录xls表格提取信息
python
工艺资源1 小时前
外贸工艺品设计参考平台众多,哪家专业值得了解
人工智能·python
无糖冰可乐211 小时前
安装wsl2,并链接Windows上的vscode运行项目
pytorch·vscode·python·pip
汤米粥1 小时前
Python爬虫中Xpath用法之——normalize-space()
开发语言·python
科技道人1 小时前
记录 设置-显示大小和字体
开发语言·android设置·字体和显示大小
浮江雾1 小时前
Flutter第三节----Dart中的数据类型
android·开发语言·学习·flutter·入门·函数
想会飞的蒲公英1 小时前
回归模型怎样评估:MAE、MSE、RMSE 和 R²
人工智能·python·机器学习·数据分析·回归
weixin_422329312 小时前
AgentScope Java 项目入门 & Builder 深度解读
java·开发语言·人工智能