我想使用Ruby从一个文件夹中获得所有文件名。


当前回答

如果您想获得包含符号链接的文件名数组,请使用

Dir.new('/path/to/dir').entries.reject { |f| File.directory? f }

甚至

Dir.new('/path/to/dir').reject { |f| File.directory? f }

如果你不想使用符号链接,请使用

Dir.new('/path/to/dir').select { |f| File.file? f }

如其他答案所示,如果你想递归地获得所有文件,使用dir .glob('/path/to/dir/**/*')而不是dir .new('/path/to/dir')。

其他回答

Dir.entries(folder)

例子:

Dir.entries(".")

来源:http://ruby-doc.org/core/classes/Dir.html method-c-entries

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(dir).select { |f| File.file?(File.join(dir, f)) }

Dir。Entries返回一个字符串数组。然后,我们必须提供文件的完整路径file .file?,除非dir等于我们当前的工作目录。这就是File.join()的原因。

这段代码只返回带扩展名的文件名(没有全局路径)

Dir.children("/path/to/search/")

= > [file_1。Rb, file_2.html, file_3.js]

如果您想获得包含符号链接的文件名数组,请使用

Dir.new('/path/to/dir').entries.reject { |f| File.directory? f }

甚至

Dir.new('/path/to/dir').reject { |f| File.directory? f }

如果你不想使用符号链接,请使用

Dir.new('/path/to/dir').select { |f| File.file? f }

如其他答案所示,如果你想递归地获得所有文件,使用dir .glob('/path/to/dir/**/*')而不是dir .new('/path/to/dir')。