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


当前回答

这是一个在目录中查找文件的解决方案:

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['/etc/path/*'].each do |file_name|
  next if File.directory? file_name 
end

这是对我有效的方法:

Dir.entries(dir).select { |f| File.file?(File.join(dir, f)) }

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

在IRB上下文中,您可以使用以下命令获取当前目录中的文件:

file_names = `ls`.split("\n")

你也可以在其他目录上这样做:

file_names = `ls ~/Documents`.split("\n")

你可能还想使用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.entries(folder)

例子:

Dir.entries(".")

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