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
相关推荐
basketball6162 分钟前
Golang:基本输入输出使用方法总结
开发语言·golang·xcode
Shingmc38 分钟前
【Linux】多路转接之epoll
linux·运维·服务器·开发语言·网络
utf8mb4安全女神15 分钟前
⽇志管理与深层防⽕墙
java·开发语言·spring boot
在学了加油17 分钟前
Inception v1学习笔记
笔记·python·学习
Mr.Lu ‍18 分钟前
QT调试查看QT内部数据时显示无可用信息,未为 Qt5Cored.dll 加载任何符号
开发语言·qt
qq_4523962321 分钟前
第九篇:《Dockerfile 指令精讲(二):WORKDIR、ENV、ARG、EXPOSE》
java·开发语言·docker
Cthy_hy22 分钟前
Python算法竞赛:集合去重+字典映射 核心用法一站式整理
数据结构·python·算法
JAVA社区22 分钟前
Java高级全套教程(九)—— SpringCloud超详细实战详解
java·开发语言·后端·spring cloud·面试·职场和发展
索西引擎23 分钟前
【langchain 1.0】ChromaDB 原生 API 实战:为 LangChain 向量库打造管理工具集
python·ai·langchain
Sirius.z24 分钟前
第J6周:Inception v1算法实战
python