遍历一个目录中的每个文件

时间:2010-03-24 23:43:13

标签: ruby directory filesystems

如何在ruby中编写循环以便我可以在每个文件上执行一段代码?

我是ruby的新手,我得出结论,这样做的方法是做每个循环 ruby文件将从与我想要循环的目录不同的目录执行。

我已经尝试了Dir.foreach,我无法让它发挥作用。

8 个答案:

答案 0 :(得分:414)

正如其他人所说,Dir.foreach在这里是个不错的选择。但请注意,Dir.entriesDir.foreach将始终显示...(当前和父目录)。你通常不想对它们进行处理,所以你可以这样做:

Dir.foreach('/path/to/dir') do |item|
  next if item == '.' or item == '..'
  # do work on real items
end

Dir.foreachDir.entries也会显示目录中的所有项目 - 隐藏和非隐藏。通常这是你想要的,但如果不是,你需要做一些事情来跳过隐藏的文件和目录。

或者,您可能希望查看提供简单通配符匹配的Dir.glob

Dir.glob('/path/to/dir/*.rb') do |rb_file|
  # do work on files ending in .rb in the desired directory
end

答案 1 :(得分:95)

这是我最喜欢的易读方法:

Dir.glob("*/*.txt") do |my_text_file|
  puts "working on: #{my_text_file}..."
end

你甚至可以扩展它来处理子目录中的所有文件:

Dir.glob("**/*.txt") do |my_text_file| # note one extra "*"
  puts "working on: #{my_text_file}..."
end

答案 2 :(得分:28)

Dir还有更短的语法来从目录中获取所有文件的数组:

Dir['dir/to/files/*'].each do |fname|
    # do something with fname
end

答案 3 :(得分:24)

Dir.foreach("/home/mydir") do |fname|
  puts fname
end

答案 4 :(得分:12)

find库专为此任务而设计: https://ruby-doc.org/stdlib-2.5.1/libdoc/find/rdoc/Find.html

require 'find'
Find.find(path) do |file|
  # process
end

这是一个标准的ruby库,所以它应该可用

答案 5 :(得分:6)

我喜欢这个,上面没有提到过。

require 'pathname'

Pathname.new('/my/dir').children.each do |path|
    puts path
end

好处是你得到一个Pathname对象而不是一个字符串,你可以用它来做更多的东西并进一步遍历。

答案 6 :(得分:3)

Dir.new('/my/dir').each do |name|
  ...
end

答案 7 :(得分:1)

要跳过...,可以使用Dir::each_child

Dir.each_child('/path/to/dir') do |filename|
  puts filename
end

Dir::children返回一个文件名数组。