我想使用Ruby从一个文件夹中获得所有文件名。
当前回答
在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
其他回答
当加载操作目录中的所有文件名时,您可以使用
Dir.glob (*)
这将返回应用程序正在运行的上下文中的所有文件(注意,对于Rails,这是应用程序的顶级目录)
您可以在这里(https://ruby-doc.org/core-2.7.1/Dir.html#method-c-glob)进行额外的匹配和递归搜索
这是一个在目录中查找文件的解决方案:
files = Dir["/work/myfolder/**/*.txt"]
files.each do |file_name|
if !File.directory? file_name
puts file_name
File.open(file_name) do |file|
file.each_line do |line|
if line =~ /banco1/
puts "Found: #{line}"
end
end
end
end
end
Dir.entries(folder)
例子:
Dir.entries(".")
来源:http://ruby-doc.org/core/classes/Dir.html method-c-entries
您还有快捷方式选项
Dir["/path/to/search/*"]
如果你想在任何文件夹或子文件夹中找到所有Ruby文件:
Dir["/path/to/search/**/*.rb"]
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
返回文件在目录和所有子目录中的相对路径
推荐文章
- 是否可以在MiniTest中运行单个测试?
- 如何在Ruby中生成a和b之间的随机数?
- 如何在Python中获得所有直接子目录
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- 无法安装gem -未能建立gem本地扩展-无法加载这样的文件——mkmf (LoadError)
- 如何复制在bash所有目录和文件递归?
- 如何在Ruby中创建文件
- 什么是Ruby文件。开放模式和选项?
- Ruby数组到字符串的转换
- 如何分割(块)一个Ruby数组成X元素的部分?
- Ruby中“or”和||的区别?
- __FILE__宏显示完整路径
- 如何测试参数是否存在在轨道
- 文件名中允许的字符
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?