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
相关推荐
不做Java程序猿好多年8 分钟前
Java中 String、StringBuffer、StringBuilder 的区别详解
开发语言·python
金銀銅鐵16 分钟前
[Python] 用 turtle 来绘制国际象棋棋盘(不含棋子)
python·游戏
這花開嗎19 分钟前
2026年TTS文字转语音API哪家强?批量自动化配音成本与技术实测
python·flask·自动化
会周易的程序员20 分钟前
js-shm: 高性能 Node.js 共享内存模块
开发语言·javascript·c++·node.js·共享内存·shm
笨蛋不要掉眼泪33 分钟前
Java虚拟机:常用参数
java·开发语言·python
happy_0x3f1 小时前
前端应用的离线暂停更新策略
开发语言·前端·php
2501_909509101 小时前
DAY 31
python
李昊哲小课1 小时前
FastAPI 猫咖预约系统 API
人工智能·python·fastapi
shylyly_1 小时前
C++中的类型转换
开发语言·c++·匿名对象·隐式类型转换·拷贝优化
你驴我1 小时前
WhatsApp 消息撤回与编辑的幂等性设计实践
java·服务器·前端·后端·python