使用Ruby从文件夹中获取所有文件的名称

5n0oy7gb  于 2022-09-21  发布在  Ruby
关注(0)|答案(20)|浏览(366)

我想使用Ruby从文件夹中获取所有文件名。

b4lqfgs4

b4lqfgs41#

您还可以使用以下快捷方式选项

Dir["/path/to/search/*"]

如果您想要在任何文件夹或子文件夹中查找所有Ruby文件:

Dir["/path/to/search/**/*.rb"]
xxhby3vn

xxhby3vn2#

Dir.entries(folder)

示例:

Dir.entries(".")

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

lrl1mhuk

lrl1mhuk3#

以下代码片断准确地显示了目录中文件的名称,跳过了子目录和"."".."点分文件夹:

Dir.entries("your/folder").select { |f| File.file? File.join("your/folder", f) }
uajslkp6

uajslkp64#

To get all files (strictly files only) recursively:

Dir.glob('path/**/*').select { |e| File.file? e }

Or anything that's not a directory (File.file? would reject non-regular files):

Dir.glob('path/**/*').reject { |e| File.directory? e }

Alternative Solution

Using Find#find over a pattern-based lookup method like Dir.glob is actually better. See this answer to "One-liner to Recursively List Directories in Ruby?".

hts6caw3

hts6caw35#

这对我很管用:

如果您不想要隐藏文件[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 }

现在,目录条目将返回隐藏文件,并且您不需要通配符Asterix(您可以只传递带有目录名的变量),但它将直接返回基本名称,因此File.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

wmtdaxz3

wmtdaxz36#

在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

qybjjes1

qybjjes17#

就我个人而言,我发现这是循环浏览文件夹中的文件最有用的,具有前瞻性的安全性:

Dir['/etc/path/*'].each do |file_name|
  next if File.directory? file_name 
end
p4tfgftt

p4tfgftt8#

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

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
5jdjgkvh

5jdjgkvh9#

此代码仅返回带扩展名的文件名(不带全局路径)

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

=>[文件_1.rb,文件_2.html,文件_3.js]

vybvopom

vybvopom10#

在获取目录中的所有文件名时,此代码片段可用于拒绝目录[...]和以.开头的隐藏文件

files = Dir.entries("your/folder").reject {|f| File.directory?(f) || f[0].include?('.')}
pjngdqdw

pjngdqdw11#

这就是对我有效的方法:

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

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

ki1q1bka

ki1q1bka12#

Dir.new('/home/user/foldername').each { |file| puts file }
gmol1639

gmol163913#

您可能还希望使用Rake::FileList(假设您具有rake依赖项):

FileList.new('lib/*') do |file|
  p file
end

根据该接口:

文件列表是懒惰的。当给定要包括在文件列表中的可能文件的全局模式的列表时,FileList保存该模式以供以后使用,而不是搜索文件结构来查找文件。

https://docs.ruby-lang.org/en/2.1.0/Rake/FileList.html

amrnrhlw

amrnrhlw14#

一种简单的方法可能是:

dir = './' # desired directory
files = Dir.glob(File.join(dir, '**', '*')).select{|file| File.file?(file)}

files.each do |f|
    puts f
end
xxhby3vn

xxhby3vn15#

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

从目录和所有子目录返回文件的相对路径

相关问题