我想使用Ruby从一个文件夹中获得所有文件名。
当前回答
你可能还想使用Rake::FileList(如果你有Rake依赖):
FileList.new('lib/*') do |file|
p file
end
根据API:
filelist是懒惰的。当给出可能的glob模式列表时 要包含在文件列表中的文件,而不是搜索文件 结构来查找文件,FileList保存后者的模式 使用。
https://docs.ruby-lang.org/en/2.1.0/Rake/FileList.html
其他回答
要递归地获取所有文件(严格来说只针对文件):
Dir.glob('path/**/*').select { |e| File.file? e }
或者任何不是目录的东西(File.file?将拒绝非常规文件):
Dir.glob('path/**/*').reject { |e| File.directory? e }
可选择的解决方案
在Dir等基于模式的查找方法上使用Find# Find。Glob实际上更好。请参阅“用Ruby递归列出目录的一行程序?”
def get_path_content(dir)
queue = Queue.new
result = []
queue << dir
until queue.empty?
current = queue.pop
Dir.entries(current).each { |file|
full_name = File.join(current, file)
if not (File.directory? full_name)
result << full_name
elsif file != '.' and file != '..'
queue << full_name
end
}
end
result
end
返回文件在目录和所有子目录中的相对路径
下面的代码片段精确地显示了目录内的文件名称,跳过子目录和“。”,“..”带点的文件夹:
Dir.entries("your/folder").select { |f| File.file? File.join("your/folder", f) }
在Ruby 2.5中,你现在可以使用Dir.children。它以数组的形式获取文件名,除了"."和".."
例子:
Dir.children("testdir") #=> ["config.h", "main.rb"]
http://ruby-doc.org/core-2.5.0/Dir.html#method-c-children
这对我来说很管用:
如果你不想要隐藏文件[1],使用Dir[]:
# With a relative path, Dir[] will return relative paths
# as `[ './myfile', ... ]`
#
Dir[ './*' ].select{ |f| File.file? f }
# Want just the filename?
# as: [ 'myfile', ... ]
#
Dir[ '../*' ].select{ |f| File.file? f }.map{ |f| File.basename f }
# Turn them into absolute paths?
# [ '/path/to/myfile', ... ]
#
Dir[ '../*' ].select{ |f| File.file? f }.map{ |f| File.absolute_path f }
# With an absolute path, Dir[] will return absolute paths:
# as: [ '/home/../home/test/myfile', ... ]
#
Dir[ '/home/../home/test/*' ].select{ |f| File.file? f }
# Need the paths to be canonical?
# as: [ '/home/test/myfile', ... ]
#
Dir[ '/home/../home/test/*' ].select{ |f| File.file? f }.map{ |f| File.expand_path f }
现在,Dir。条目将返回隐藏的文件,并且您不需要通配符asterix(您可以直接将目录名传递给变量),但它将直接返回basename,因此File. xml将返回文件。XXX函数不能工作。
# In the current working dir:
#
Dir.entries( '.' ).select{ |f| File.file? f }
# In another directory, relative or otherwise, you need to transform the path
# so it is either absolute, or relative to the current working dir to call File.xxx functions:
#
home = "/home/test"
Dir.entries( home ).select{ |f| File.file? File.join( home, f ) }
[1] .dotfile在unix上,我不知道Windows上
推荐文章
- 是否可以在MiniTest中运行单个测试?
- 如何在Ruby中生成a和b之间的随机数?
- 如何在Python中获得所有直接子目录
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- 无法安装gem -未能建立gem本地扩展-无法加载这样的文件——mkmf (LoadError)
- 如何复制在bash所有目录和文件递归?
- 如何在Ruby中创建文件
- 什么是Ruby文件。开放模式和选项?
- Ruby数组到字符串的转换
- 如何分割(块)一个Ruby数组成X元素的部分?
- Ruby中“or”和||的区别?
- __FILE__宏显示完整路径
- 如何测试参数是否存在在轨道
- 文件名中允许的字符
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?