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

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

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

wmtdaxz3

wmtdaxz316#

在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

hts6caw3

hts6caw317#

这对我很管用:

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

uajslkp6

uajslkp618#

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?".

lrl1mhuk

lrl1mhuk19#

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

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

xxhby3vn20#

Dir.entries(folder)

示例:

Dir.entries(".")

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

相关问题