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
相关推荐
酷可达拉斯4 小时前
Linux操作系统-shell编程(0)
linux·运维·服务器·python·云计算
W658034194 小时前
2026年AI编程工具实测横评:Claude Code v2.1、Cursor 3.0、Trae SOLO、Copilot、Windsurf 谁更好用?
python·copilot·ai编程
深念Y4 小时前
开发者如何清理和迁移C盘堆积的垃圾
c语言·开发语言
snow@li4 小时前
技术栈对应:Vue (前端) + SpringBoot (Java 后端) =》 Python 全场景配套
python
2501_909509104 小时前
DAY 28
开发语言·python
码云骑士4 小时前
71-Agent记忆系统-短期记忆-长期记忆-向量知识库三层架构
python·架构
卷无止境4 小时前
Python 的 exec 与 eval :动态代码执行的能力、风险与工程实践
后端·python
user-猴子4 小时前
从零构建 2048 游戏,解析“Python-Use”范式的完整闭环
开发语言·python·游戏
郝学胜_神的一滴4 小时前
Python 高级编程 025:二分利器bisect模块:优雅维系有序序列,极致优化检索性能
python·pycharm
qq_401700414 小时前
Qt容器性能优化:QVector、QHash、QMap到底应该怎么选?
开发语言·qt·性能优化