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


当前回答

就我个人而言,我发现这对于在文件夹中循环文件最有用,前瞻性安全:

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

其他回答

就我个人而言,我发现这对于在文件夹中循环文件最有用,前瞻性安全:

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

这对我来说很管用:

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

现在,Dir。条目将返回隐藏的文件,并且您不需要通配符asterix(您可以直接将目录名传递给变量),但它将直接返回basename,因此File. xml将返回文件。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上

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

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')。

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

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

如果你用空格创建目录:

mkdir "a b"
touch "a b/c"

你不需要转义目录名,它会自动完成:

p Dir["a b/*"] # => ["a b/c"]