有没有人知道Ruby中是否存在现有的模块/函数来遍历文件系统目录和文件?我正在寻找类似Python的东西os.walk.我发现的最接近的模块是Find需要一些额外的工作来进行遍历.
Python代码如下所示:
for root, dirs, files in os.walk('.'):
for name in files:
print name
for name in dirs:
print name
Run Code Online (Sandbox Code Playgroud)
ACo*_*lie 24
以下将递归打印所有文件.那你可以使用File.directory吗?查看它是目录还是文件.
Dir['**/*'].each { |f| print f }
Run Code Online (Sandbox Code Playgroud)
require 'pathname'
def os_walk(dir)
root = Pathname(dir)
files, dirs = [], []
Pathname(root).find do |path|
unless path == root
dirs << path if path.directory?
files << path if path.file?
end
end
[root, files, dirs]
end
root, files, dirs = os_walk('.')
Run Code Online (Sandbox Code Playgroud)