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
相关推荐
闻缺陷则喜何志丹8 分钟前
【二分查找】P9822 [ICPC2020 Shanghai R] Walker【有误差】|普及
开发语言·算法·r语言
十五年专注C++开发8 分钟前
C++ union 的一种妙用法
开发语言·c++
hui函数10 分钟前
python全栈入门到实战【基础篇 02】环境搭建:Python解释器与PyCharm、VSCode编辑器安装配置详解
开发语言·python
venus6013 分钟前
上海计算机学会2025年8月月赛丙组T1镜像加密题解
开发语言·c++·算法
weixin_3903084615 分钟前
Ubuntu运行python程序步骤
python
智航GIS17 分钟前
8.9 装饰器
开发语言·python
我命由我1234522 分钟前
LangChain 学习 - Langchain Model IO(环境安装、大模型应用开发、模型分类、模型消息)
人工智能·python·ai·语言模型·pycharm·langchain·python3.11
萧曵 丶23 分钟前
Java 线程池优化
java·开发语言
0和1的舞者23 分钟前
Python库使用全攻略:从入门到实战
python·学习·知识·案例
YJlio24 分钟前
PsPing 学习笔记(14.6):直方图视图——可视化延迟分布与抖动
开发语言·笔记·python·学习·eclipse·pdf·github